public static JsonData DataTableToJson(DataTable dt) { JsonData jsdata = new JsonData(); try { StringBuilder sb = new StringBuilder(); LitJson.JsonWriter jw = new LitJson.JsonWriter(sb); jw.WriteArrayStart(); foreach (DataRow dr in dt.Rows) { jw.WriteObjectStart(); foreach (DataColumn dc in dt.Columns) { jw.WritePropertyName(dc.ColumnName); jw.Write(dr[dc.ColumnName].ToString()); } jw.WriteObjectEnd(); } jw.WriteArrayEnd(); jsdata = JsonMapper.ToObject(sb.ToString()); } catch (System.Exception ex) { } return(jsdata); }
public static void LitJsonWriterObjects () { for (int j = 0; j < Common.Iterations; j++) { StringBuilder output = new StringBuilder (); JsonWriter writer = new JsonWriter (new StringWriter (output)); int n = Common.SampleObject.Length; for (int i = 0; i < n; i += 2) { switch ((char) Common.SampleObject[i]) { case '{': writer.WriteObjectStart (); break; case '}': writer.WriteObjectEnd (); break; case '[': writer.WriteArrayStart (); break; case ']': writer.WriteArrayEnd (); break; case 'P': writer.WritePropertyName ( (string) Common.SampleObject[i + 1]); break; case 'I': writer.Write ( (int) Common.SampleObject[i + 1]); break; case 'D': writer.Write ( (double) Common.SampleObject[i + 1]); break; case 'S': writer.Write ( (string) Common.SampleObject[i + 1]); break; case 'B': writer.Write ( (bool) Common.SampleObject[i + 1]); break; case 'N': writer.Write (null); break; } } } }
public void ErrorObjectClosingTest() { JsonWriter writer = new JsonWriter (); writer.WriteObjectStart (); writer.WritePropertyName ("foo"); writer.Write ("bar"); writer.WriteArrayEnd (); }
public void ErrorExcessDataTest() { JsonWriter writer = new JsonWriter (); writer.WriteArrayStart (); writer.Write (true); writer.WriteArrayEnd (); writer.Write (false); }
public static void WriteField(this LitJson.JsonWriter writer, string propertyName, string[] value) { propertyName = propertyName.Replace(".", "#"); writer.WritePropertyName(propertyName); writer.WriteArrayStart(); for (int i = 0; i < value.Length; i++) { writer.Write(value[i]); } writer.WriteArrayEnd(); }
public static void ToNetMsg(Dictionary<long, F3_NetServerInfo> servers, ref NetOutgoingMessage netMsg) { netMsg.Write((byte)NetDataType.eDATA_REQUEST_SERVER_LIST); StringBuilder sb = new StringBuilder(); JsonWriter writer = new JsonWriter(sb); writer.WriteObjectStart(); writer.WritePropertyName("servers"); writer.WriteArrayStart(); for (int i = 0; i < servers.Count; i++) { F3_NetServerInfo info = servers.ElementAt(i).Value; writer.WriteObjectStart(); writer.WritePropertyName("UUID"); writer.Write(servers.ElementAt(i).Key); writer.WritePropertyName("serverName"); writer.Write(info.m_serverName); writer.WritePropertyName("type"); writer.Write((int)info.m_serverType); writer.WritePropertyName("internal_ip"); writer.Write(info.m_serverInternalAdress.Address.ToString()); writer.WritePropertyName("internal_port"); writer.Write(info.m_serverInternalAdress.Port); writer.WritePropertyName("external_ip"); writer.Write(info.m_serverExternalAdress.Address.ToString()); writer.WritePropertyName("external_port"); writer.Write(info.m_serverExternalAdress.Port); writer.WritePropertyName("maxPlayers"); writer.Write(info.m_maxPlayers); writer.WritePropertyName("currentPlayers"); writer.Write(info.m_currentNbPlayers); writer.WritePropertyName("token"); writer.Write(info.m_NATtoken); writer.WriteObjectEnd(); } writer.WriteArrayEnd(); writer.WriteObjectEnd(); netMsg.Write(sb.ToString()); }
public void BooleansTest() { JsonWriter writer = new JsonWriter (); writer.WriteArrayStart (); writer.Write (true); writer.Write (false); writer.Write (false); writer.Write (true); writer.WriteArrayEnd (); }
public static void LitJsonWriterNumbers () { for (int i = 0; i < Common.Iterations; i++) { StringBuilder output = new StringBuilder (); JsonWriter writer = new JsonWriter (new StringWriter (output)); writer.WriteArrayStart (); foreach (int n in Common.SampleInts) writer.Write (n); foreach (double n in Common.SampleDoubles) writer.Write (n); writer.WriteArrayEnd (); } }
public static Boolean AddJsonArray(string name, ref JsonData targetjsondata) { Boolean bRet = false; if (targetjsondata != null) { StringBuilder sb = new StringBuilder(targetjsondata.ToJson()); LitJson.JsonWriter jw = new LitJson.JsonWriter(sb); jw.WriteArrayStart(); //jw.Write("{}"); jw.WriteArrayEnd(); targetjsondata[name] = JsonMapper.ToObject(sb.ToString()); targetjsondata[name].SetJsonType(JsonType.Array); bRet = true; } return(bRet); }
public string ListStepDefinitionsAsJson() { StringBuilder sb = new StringBuilder(); JsonWriter writer = new JsonWriter(sb); writer.WriteArrayStart(); foreach (StepDefinition sd in _stepDefinitions) { writer.WriteObjectStart(); writer.WritePropertyName("id"); writer.Write(sd.Id); writer.WritePropertyName("regexp"); writer.Write(sd.Pattern); writer.WriteObjectEnd(); } writer.WriteArrayEnd(); return sb.ToString(); }
public void NullTextWriterTest() { JsonWriter writer = new JsonWriter (TextWriter.Null); writer.WriteArrayStart (); writer.Write ("Hello"); writer.Write ("World"); writer.WriteArrayEnd (); }
public static string JMap(Map m) { LitJson.JsonWriter js = new LitJson.JsonWriter(); js.PrettyPrint = true; js.IndentValue = 2; js.WriteObjectStart(); js.WritePropertyName("min"); js.WriteObjectStart(); js.WritePropertyName("x"); js.Write(m.min.x); js.WritePropertyName("y"); js.Write(m.min.y); js.WriteObjectEnd(); js.WritePropertyName("max"); js.WriteObjectStart(); js.WritePropertyName("x"); js.Write(m.max.x); js.WritePropertyName("y"); js.Write(m.max.y); js.WriteObjectEnd(); js.WritePropertyName("tiles"); js.WriteArrayStart(); List<Map.Tile> tiles = m.GetTiles(); foreach(Map.Tile t in tiles) { js.WriteObjectStart(); // Key js.WritePropertyName("key"); js.WriteObjectStart(); js.WritePropertyName("x"); js.Write(t.hexCoord.x); js.WritePropertyName("y"); js.Write (t.hexCoord.y); js.WriteObjectEnd(); //End of Key // Value js.WritePropertyName("value"); js.WriteObjectStart(); js.WritePropertyName("tileType"); js.Write(t.spriteType.ToString()); js.WritePropertyName("penalty"); js.Write(t.penalty.ToString()); js.WritePropertyName("visibility"); js.Write(t.visibility.ToString()); js.WriteObjectEnd(); // End of Value js.WriteObjectEnd(); } js.WriteArrayEnd(); js.WritePropertyName("towns"); js.WriteArrayStart(); List<Map.Town> towns = m.GetTowns(); foreach (Map.Town t in towns) { js.WriteObjectStart(); // Key js.WritePropertyName("key"); js.WriteObjectStart(); js.WritePropertyName("x"); js.Write(t.hexCoord.x); js.WritePropertyName("y"); js.Write (t.hexCoord.y); js.WriteObjectEnd(); // End of Key // Value js.WritePropertyName("value"); js.WriteObjectStart(); js.WritePropertyName("playerSide"); js.Write(t.team); js.WriteObjectEnd(); // End of Value js.WriteObjectEnd(); } js.WriteArrayEnd(); // TODO Units js.WriteObjectEnd(); return js.ToString(); }
public void NestedArraysTest() { JsonWriter writer = new JsonWriter (); string json = "[1,[\"a\",\"b\",\"c\"],2,[[null]],3]"; writer.WriteArrayStart (); writer.Write (1); writer.WriteArrayStart (); writer.Write ("a"); writer.Write ("b"); writer.Write ("c"); writer.WriteArrayEnd (); writer.Write (2); writer.WriteArrayStart (); writer.WriteArrayStart (); writer.Write (null); writer.WriteArrayEnd (); writer.WriteArrayEnd (); writer.Write (3); writer.WriteArrayEnd (); Assert.AreEqual (writer.ToString (), json); }
private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj.IsString) { writer.Write(obj.GetString()); return; } if (obj.IsBoolean) { writer.Write(obj.GetBoolean()); return; } if (obj.IsDouble) { writer.Write(obj.GetDouble()); return; } if (obj.IsInt) { writer.Write(obj.GetInt()); return; } if (obj.IsLong) { writer.Write(obj.GetLong()); return; } if (obj.IsArray) { writer.WriteArrayStart(); IEnumerator enumerator = obj.GetEnumerator(); try { while (enumerator.MoveNext()) { object obj2 = enumerator.Current; JsonData.WriteJson((JsonData)obj2, writer); } } finally { IDisposable disposable; if ((disposable = (enumerator as IDisposable)) != null) { disposable.Dispose(); } } writer.WriteArrayEnd(); return; } if (obj.IsObject) { writer.WriteObjectStart(); IDictionaryEnumerator enumerator2 = obj.GetEnumerator(); try { while (enumerator2.MoveNext()) { object obj3 = enumerator2.Current; DictionaryEntry dictionaryEntry = (DictionaryEntry)obj3; writer.WritePropertyName((string)dictionaryEntry.Key); JsonData.WriteJson((JsonData)dictionaryEntry.Value, writer); } } finally { IDisposable disposable2; if ((disposable2 = (enumerator2 as IDisposable)) != null) { disposable2.Dispose(); } } writer.WriteObjectEnd(); return; } }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > JsonMapper.max_nesting_depth) { throw new JsonException(string.Format("Max allowed object depth reached while trying to export from type {0}", (object)obj.GetType())); } if (obj == null) { writer.Write((string)null, true); } else if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } } else if (obj is string) { writer.Write((string)obj, true); } else if (obj is double) { writer.Write((double)obj); } else if (obj is int) { writer.Write((int)obj); } else if (obj is bool) { writer.Write((bool)obj); } else if (obj is long) { writer.Write((long)obj); } else if (obj is Array) { writer.WriteArrayStart(); foreach (object obj1 in (Array)obj) { JsonMapper.WriteValue(obj1, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); } else if (obj is IList) { writer.WriteArrayStart(); foreach (object obj1 in (IEnumerable)obj) { JsonMapper.WriteValue(obj1, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); } else if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry dictionaryEntry in (IDictionary)obj) { writer.WritePropertyName((string)dictionaryEntry.Key); JsonMapper.WriteValue(dictionaryEntry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); } else { Type type = obj.GetType(); if (JsonMapper.custom_exporters_table.ContainsKey(type)) { JsonMapper.custom_exporters_table[type](obj, writer); } else if (JsonMapper.base_exporters_table.ContainsKey(type)) { JsonMapper.base_exporters_table[type](obj, writer); } else if (obj is Enum) { Type underlyingType = Enum.GetUnderlyingType(type); if (underlyingType == typeof(long) || underlyingType == typeof(uint) || underlyingType == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } } else { JsonMapper.AddTypeProperties(type); IList <PropertyMetadata> typeProperty = JsonMapper.type_properties[type]; writer.WriteObjectStart(); foreach (PropertyMetadata propertyMetadata in (IEnumerable <PropertyMetadata>)typeProperty) { if (propertyMetadata.IsField) { writer.WritePropertyName(propertyMetadata.Info.Name); JsonMapper.WriteValue(((FieldInfo)propertyMetadata.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo info = (PropertyInfo)propertyMetadata.Info; if (info.CanRead) { writer.WritePropertyName(propertyMetadata.Info.Name); JsonMapper.WriteValue(info.GetValue(obj, (object[])null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); } } }
private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.Contains(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type] as ExporterFunc; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.Contains(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type] as ExporterFunc; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList props = type_properties[obj_type] as IList; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Info.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); }
public void UpdateIssue(IssueUpdate update, NetworkCredential credential, Action<string> stdout, Action<string> stderr) { var client = new WebClient(); client.Headers.Add("Content-Type", "application/json"); client.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credential.UserName + ":" + credential.Password))); var jsonRPCQuery = new JsonWriter(); jsonRPCQuery.WriteObjectStart(); jsonRPCQuery.WritePropertyName("method"); jsonRPCQuery.Write("ticket.update"); jsonRPCQuery.WritePropertyName("params"); jsonRPCQuery.WriteArrayStart(); jsonRPCQuery.Write(update.Issue.Id); jsonRPCQuery.Write(update.Comment); jsonRPCQuery.WriteObjectStart(); jsonRPCQuery.WritePropertyName("action"); jsonRPCQuery.Write("resolve"); jsonRPCQuery.WritePropertyName("action_resolve_resolve_resolution"); jsonRPCQuery.Write("fixed"); jsonRPCQuery.WriteObjectEnd(); jsonRPCQuery.Write(true); jsonRPCQuery.WriteArrayEnd(); jsonRPCQuery.WriteObjectEnd(); client.UploadString(this.RPCUrl(), jsonRPCQuery.ToString()); }
public void WriteValue(JsonWriter writer, string typeName, object value, string format) { writer.WriteObjectStart(); writer.WritePropertyName("$type"); writer.Write(typeName); if (typeName == "dateTime") { if (String.IsNullOrEmpty(format)) format = DateTimeIso8601Format; writer.WritePropertyName("format"); writer.Write(format); writer.WritePropertyName("value"); writer.Write(((DateTime)value).ToString(format)); } else if (typeName == "dataAddress") { DataAddress dataAddress = (DataAddress)value; writer.WritePropertyName("block-id"); writer.Write(dataAddress.BlockId); writer.WritePropertyName("data-id"); writer.Write(dataAddress.DataId); } else if (typeName == "serviceAddress") { IServiceAddress serviceAddress = (IServiceAddress)value; writer.WritePropertyName("address"); writer.Write(serviceAddress.ToString()); } else if (typeName == "singleNodeSet" || typeName == "compressedNodeSet") { NodeSet nodeSet = (NodeSet)value; writer.WritePropertyName("nids"); writer.WriteArrayStart(); for (int i = 0; i < nodeSet.NodeIds.Length; i++) { writer.Write(nodeSet.NodeIds[i]); } writer.WriteArrayEnd(); writer.WritePropertyName("data"); string base64Data = Convert.ToBase64String(nodeSet.Buffer); writer.Write(base64Data); } else { throw new FormatException(); } writer.WriteObjectEnd(); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException($"Max allowed object depth reached while trying to export from type {obj.GetType()}"); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is string) { writer.Write((string)obj); return; } if (obj is double) { writer.Write((double)obj); return; } if (obj is int) { writer.Write((int)obj); return; } if (obj is bool) { writer.Write((bool)obj); return; } if (obj is long) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object item in (Array)obj) { WriteValue(item, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object item2 in (IList)obj) { WriteValue(item2, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry item3 in (IDictionary)obj) { writer.WritePropertyName((string)item3.Key); WriteValue(item3.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type type = obj.GetType(); if (custom_exporters_table.ContainsKey(type)) { ExporterFunc exporterFunc = custom_exporters_table[type]; exporterFunc(obj, writer); return; } if (base_exporters_table.ContainsKey(type)) { ExporterFunc exporterFunc = base_exporters_table[type]; exporterFunc(obj, writer); return; } if (obj is Enum) { Type underlyingType = Enum.GetUnderlyingType(type); if (underlyingType == typeof(long) || underlyingType == typeof(uint) || underlyingType == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } AddTypeProperties(type); IList <PropertyMetadata> list = type_properties[type]; writer.WriteObjectStart(); foreach (PropertyMetadata item4 in list) { if ((item4.Ignore & JsonIgnoreWhen.Serializing) > JsonIgnoreWhen.Never) { continue; } if (item4.IsField) { writer.WritePropertyName(item4.Info.Name); WriteValue(((FieldInfo)item4.Info).GetValue(obj), writer, writer_is_private, depth + 1); continue; } PropertyInfo propertyInfo = (PropertyInfo)item4.Info; if (propertyInfo.CanRead) { writer.WritePropertyName(item4.Info.Name); WriteValue(propertyInfo.GetValue(obj, null), writer, writer_is_private, depth + 1); } } writer.WriteObjectEnd(); }
private void Serialize(Message message, JsonWriter writer, bool inStream) { if (!inStream) { writer.WriteObjectStart(); writer.WritePropertyName("jsonrpc"); writer.Write("1.0"); } if (message.Attributes.Contains("id")) { writer.WritePropertyName("id"); // TODO: we presume is a number castable to int4 ... writer.Write((int)message.Attributes["id"]); } if (message is MessageStream) { writer.WritePropertyName("stream"); writer.WriteArrayStart(); foreach (Message m in ((MessageStream)message)) { Serialize(m, writer, true); } writer.WriteArrayEnd(); } else if (message.MessageType == MessageType.Request) { writer.WritePropertyName("method"); writer.Write(message.Name); writer.WritePropertyName("params"); writer.WriteArrayStart(); foreach (MessageArgument argument in message.Arguments) { WriteValue(argument, writer); } writer.WriteArrayEnd(); } else { writer.WritePropertyName("result"); IList<MessageArgument> args = message.Arguments; if (args.Count == 0) { writer.Write(null); } else if (args.Count == 1) { if (message.HasError) { writer.Write(null); writer.WritePropertyName("error"); writer.WriteObjectStart(); writer.WritePropertyName("message"); writer.Write(message.ErrorMessage); writer.WritePropertyName("source"); writer.Write(message.Error.Source); writer.WritePropertyName("stackTrace"); //TODO: does the string needs to be normalized? writer.Write(message.ErrorStackTrace); writer.WriteObjectEnd(); } else { WriteValue(args[0], writer); writer.WritePropertyName("error"); writer.Write(null); } } else { // here we are sure we don't have an error, so skip // any check about it writer.WriteArrayStart(); foreach (MessageArgument argument in message.Arguments) { WriteValue(argument, writer); } writer.WriteArrayEnd(); } } if (!inStream) writer.WriteObjectEnd(); }
private void WriteValue(object value, string format, JsonWriter writer) { // JSON defined types if (value == null || value == DBNull.Value) writer.Write(null); else if (value is string) writer.Write((string)value); else if (value is short) writer.Write((short)value); else if (value is int) writer.Write((int)value); else if (value is long) writer.Write((long)value); else if (value is float) writer.Write((float)value); else if (value is double) writer.Write((double)value); else if (value is decimal) writer.Write((decimal)value); else if (value is bool) writer.Write((bool)value); else if (value is Array) { writer.WriteArrayStart(); Array array = (Array)value; for (int i = 0; i < array.Length; i++) { object arrayValue = array.GetValue(i); WriteValue(arrayValue, null, writer); } writer.WriteArrayEnd(); } else { IJsonRpcTypeResolver resolver; string typeName = ResolveTypeName(value, out resolver); resolver.WriteValue(writer, typeName, value, format); } }
private void ReadInto(JsonReader reader, JsonWriter jsonWriter, bool firstLevel, out Type type, out IJsonRpcTypeResolver resolver) { type = null; resolver = null; while (reader.Read()) { if (reader.Token == JsonToken.PropertyName) { string propertyName = (string)reader.Value; if (firstLevel && propertyName == "$type") { if (!reader.Read()) throw new FormatException(); if (reader.Token != JsonToken.String) throw new FormatException(); string typeString = (string)reader.Value; type = ResolveType(typeString, out resolver); if (type == null) throw new FormatException(); } else { jsonWriter.WritePropertyName(propertyName); } } else if (reader.Token == JsonToken.Boolean) { jsonWriter.Write((bool)reader.Value); } else if (reader.Token == JsonToken.Int) { jsonWriter.Write((int)reader.Value); } else if (reader.Token == JsonToken.Long) { jsonWriter.Write((long)reader.Value); } else if (reader.Token == JsonToken.Double) { jsonWriter.Write((double)reader.Value); } else if (reader.Token == JsonToken.String) { jsonWriter.Write((string)reader.Value); } else if (reader.Token == JsonToken.Null) { jsonWriter.Write(null); } else if (reader.Token == JsonToken.ArrayStart) { jsonWriter.WriteArrayStart(); while (reader.Read()) { Type dummyType; IJsonRpcTypeResolver dummyResolver; ReadInto(reader, jsonWriter, false, out dummyType, out dummyResolver); if (reader.Token == JsonToken.ArrayEnd) { jsonWriter.WriteArrayEnd(); break; } } } else if (reader.Token == JsonToken.ObjectEnd) { jsonWriter.WriteObjectEnd(); break; } } }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth, bool hex) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(); return; } if (obj is IJsonReader) { ((IJsonReader)obj).OnObjectToJsonStarted(); } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is String) { writer.Write((string)obj, hex); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1, hex); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteValue(elem, writer, writer_is_private, depth + 1, hex); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { writer.WritePropertyName(entry.Key.ToString(), hex); WriteValue(entry.Value, writer, writer_is_private, depth + 1, hex); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { object[] objs = p_data.Info.GetCustomAttributes(typeof(JsonNonFieldAttribute), false); if (objs.Length > 0) { continue; } if (p_data.IsField) { writer.WritePropertyName(p_data.Info.Name, hex); WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1, hex); } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; if (p_info.CanRead) { try { writer.WritePropertyName(p_data.Info.Name, hex); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1, hex); } catch (System.Exception e) { UnityEngine.Debug.Log("property:" + p_data.Info.Name + " get faild."); } } } } writer.WriteObjectEnd(); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}{1}", obj.GetType(), obj)); } //Null handler if (obj == null) { writer.Write(null); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object FIRST as in BEFORE ANYTHING ELSE!!! Love, Mark if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } /*** Check Base Types ***/ if (obj.GetType().ToString() == "System.MonoType") { writer.Write(obj.ToString()); return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { Type valueType = obj.GetType().GetGenericArguments()[0]; writer.WriteArrayStart(); foreach (object elem in (IList)obj) { if (!valueType.IsAbstract) { WriteValue(elem, writer, writer_is_private, depth + 1); } else { writer.WriteObjectStart(); writer.WritePropertyName(elem.GetType().ToString()); WriteValue(elem, writer, writer_is_private, depth + 1); writer.WriteObjectEnd(); } } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); IDictionary dict = (IDictionary)obj; Type curType = obj.GetType(); bool isDict = typeof(IDictionary).IsAssignableFrom(curType); while (isDict) { isDict = typeof(IDictionary).IsAssignableFrom(curType.BaseType); if (isDict) { curType = curType.BaseType; } } Type valueType = curType.GetGenericArguments()[1]; foreach (DictionaryEntry entry in dict) { //This next line means we can't have anything but base types as keys. Love, Mark //writer.WritePropertyName (entry.Key.ToString()); if (IsBaseType(entry.Key)) { writer.WritePropertyName(entry.Key.ToString()); } else { JsonWriter newWriter = new JsonWriter(); JsonMapper.ToJson(entry.Key, newWriter); //string key = writer.JsonToString(newWriter.ToString()); string key = newWriter.ToString(); writer.WritePropertyName(key); } if (!valueType.IsAbstract) { WriteValue(entry.Value, writer, writer_is_private, depth + 1); } else { //Creates a second layer that stores the child type key of the object for decoding writer.WriteObjectStart(); if (entry.Value != null) { writer.WritePropertyName(entry.Value.GetType().ToString()); } else { writer.WritePropertyName("null"); } WriteValue(entry.Value, writer, writer_is_private, depth + 1); writer.WriteObjectEnd(); } } writer.WriteObjectEnd(); return; } /*Type obj_type = obj.GetType (); * * // See if there's a custom exporter for the object * if (custom_exporters_table.ContainsKey (obj_type)) { * ExporterFunc exporter = custom_exporters_table[obj_type]; * exporter (obj, writer); * * return; * }*/ // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { bool skip = false; bool force = false; System.Object[] attrs = p_data.Info.GetCustomAttributes(false); if (attrs.Length > 0) { for (int j = 0; j < attrs.Length; j++) { if (attrs[j].GetType() == typeof(SkipSerialization)) { skip = true; break; } if (attrs[j].GetType() == typeof(ForceSerialization)) { force = true; break; } } } if (skip) { continue; } if (p_data.IsField) { FieldInfo f_info = ((FieldInfo)p_data.Info); if (f_info.GetValue(obj) == null && !force) { continue; } writer.WritePropertyName(p_data.Info.Name); if (f_info.FieldType.IsAbstract) { writer.WriteObjectStart(); writer.WritePropertyName(f_info.GetValue(obj).GetType().ToString()); depth++; } WriteValue(f_info.GetValue(obj), writer, writer_is_private, depth + 1); if (f_info.FieldType.IsAbstract) { writer.WriteObjectEnd(); } } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; if (p_info.CanRead) { object propertyValue = GetPropertyValue(obj, p_info); if (propertyValue == null && !force) { continue; } writer.WritePropertyName(p_data.Info.Name); if (p_info.PropertyType.IsAbstract) { writer.WriteObjectStart(); //writer.WritePropertyName(p_info.GetValue(obj, null).GetType().ToString()); writer.WritePropertyName(propertyValue.GetType().ToString()); depth++; } //WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); WriteValue(propertyValue, writer, writer_is_private, depth + 1); if (p_info.PropertyType.IsAbstract) { writer.WriteObjectEnd(); } } } } writer.WriteObjectEnd(); }
public void PrettyPrintTest() { JsonWriter writer = new JsonWriter (); string json = @" [ { ""precision"" : ""zip"", ""Latitude"" : 37.7668, ""Longitude"" : -122.3959, ""City"" : ""SAN FRANCISCO"" }, { ""precision"" : ""zip"", ""Latitude"" : 37.371991, ""Longitude"" : -122.02602, ""City"" : ""SUNNYVALE"" } ]"; writer.PrettyPrint = true; writer.WriteArrayStart (); writer.WriteObjectStart (); writer.WritePropertyName ("precision"); writer.Write ("zip"); writer.WritePropertyName ("Latitude"); writer.Write (37.7668); writer.WritePropertyName ("Longitude"); writer.Write (-122.3959); writer.WritePropertyName ("City"); writer.Write ("SAN FRANCISCO"); writer.WriteObjectEnd (); writer.IndentValue = 2; writer.WriteObjectStart (); writer.WritePropertyName ("precision"); writer.Write ("zip"); writer.WritePropertyName ("Latitude"); writer.Write (37.371991); writer.WritePropertyName ("Longitude"); writer.Write (-122.02602); writer.WritePropertyName ("City"); writer.Write ("SUNNYVALE"); writer.WriteObjectEnd (); writer.WriteArrayEnd (); Assert.AreEqual (writer.ToString (), json); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } #region UnityEngine specific #if UNITY3D if (obj is UnityEngine.Vector2) { writer.Write((UnityEngine.Vector2)obj); return; } if (obj is UnityEngine.Vector3) { writer.Write((UnityEngine.Vector3)obj); return; } if (obj is UnityEngine.Vector4) { writer.Write((UnityEngine.Vector4)obj); return; } if (obj is UnityEngine.Quaternion) { writer.Write((UnityEngine.Quaternion)obj); return; } if (obj is UnityEngine.Matrix4x4) { writer.Write((UnityEngine.Matrix4x4)obj); return; } if (obj is UnityEngine.Ray) { writer.Write((UnityEngine.Ray)obj); return; } if (obj is UnityEngine.RaycastHit) { writer.Write((UnityEngine.RaycastHit)obj); return; } if (obj is UnityEngine.Color) { writer.Write((UnityEngine.Color)obj); return; } #endif #endregion if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { writer.WritePropertyName((string)entry.Key); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table [obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table [obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties [obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { #if UNITY3D // Skip certain UnityEngine specific types that can't be serialized if (IsUnserializableUnityType(p_data)) { continue; } #endif if (p_data.IsField) { writer.WritePropertyName(p_data.Info.Name); WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { Debug.LogError("writer" + writer.ToString()); throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is float) { writer.Write((float)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); List <DictionaryEntry> entries = new List <DictionaryEntry>(); foreach (DictionaryEntry entry in (IDictionary)obj) { entries.Add(entry); } entries.Sort((kv1, kv2) => { return(kv1.Key.GetHashCode() - kv2.Key.GetHashCode()); if (kv1.Key is int && kv2.Key is int) { return((int)kv1.Key - (int)kv2.Key); } if (kv1.Key is IComparable && kv2.Key is IComparable) { return(((IComparable)kv1.Key).CompareTo(kv2.Key)); } return(kv1.Key.GetHashCode() - kv2.Key.GetHashCode()); }); foreach (DictionaryEntry entry in entries) { writer.WritePropertyName(entry.Key.ToString()); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type obj_type; if (obj is ILRuntime.Runtime.Intepreter.ILTypeInstance) { obj_type = ((ILRuntime.Runtime.Intepreter.ILTypeInstance)obj).Type.ReflectionType; } else if (obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType) { obj_type = ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)obj).ILInstance.Type.ReflectionType; } else { obj_type = obj.GetType(); } // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { if (((FieldInfo)p_data.Info).IsStatic || obj_type == p_data.Type) { continue; } writer.WritePropertyName(p_data.Info.Name); WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; if (/*p_info.GetAccessors(true)[0].IsStatic|| */ obj_type == p_info.PropertyType) { continue; } if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); }
static void WriteArray(JsonWriter writer, Action writeArrayDetails) { writer.WriteArrayStart(); writeArrayDetails(); writer.WriteArrayEnd(); }
public Action DownloadIssues(string project, int start, bool includeClosedIssues, Func<IEnumerable<Issue>, bool> onData, Action<DownloadProgressChangedEventArgs> onProgress, Action<bool, Exception> onCompleted) { Debug.Assert(project != null); Debug.Assert(onData != null); var client = new WebClient(); client.Headers.Add("Content-Type", "application/json"); client.UploadStringCompleted += (sender, args) => { if (args.Cancelled || args.Error != null) { if (onCompleted != null) onCompleted(args.Cancelled, args.Error); return; } JsonData data = JsonMapper.ToObject(args.Result); if (data["error"] != null) { if (onCompleted != null) onCompleted(false, new Exception((string)data["error"]["message"])); return; } else if (data["result"] != null && data["result"].Count > 0) { var client2 = new WebClient(); client2.Headers.Add("Content-Type", "application/json"); var jsonRPCQuery = new JsonWriter(); jsonRPCQuery.WriteObjectStart(); jsonRPCQuery.WritePropertyName("method"); jsonRPCQuery.Write("system.multicall"); jsonRPCQuery.WritePropertyName("params"); jsonRPCQuery.WriteArrayStart(); for (int i = 0; i < data["result"].Count - 1; i++) { jsonRPCQuery.WriteObjectStart(); jsonRPCQuery.WritePropertyName("method"); jsonRPCQuery.Write("ticket.get"); jsonRPCQuery.WritePropertyName("params"); jsonRPCQuery.WriteArrayStart(); jsonRPCQuery.Write((int)data["result"][i]); jsonRPCQuery.WriteArrayEnd(); jsonRPCQuery.WriteObjectEnd(); } client2.UploadStringCompleted += (sender2, args2) => { if (args2.Cancelled || args2.Error != null) { return; } int lastObjectStart = 0; int count = 0; bool inQuote = false; bool lastWasBackslash = false; for (int n = 1; n < args2.Result.Length; n++) { if (inQuote) { if (args2.Result[n] == '"' && !lastWasBackslash) { inQuote = false; } else if (args2.Result[n] == '\\') { lastWasBackslash = !lastWasBackslash; } else { lastWasBackslash = false; } } else { if (args2.Result[n] == '"') { inQuote = true; } else if (args2.Result[n] == '}') { --count; if (count == 0) { n++; JsonData issueData = JsonMapper.ToObject(args2.Result.Substring(lastObjectStart, n - lastObjectStart)); TracIssue[] issues = new TracIssue[1]; issues[0] = new TracIssue(); issues[0].Id = (int)issueData["result"][0]; if (issueData["result"][3].ToString().Contains("milestone")) { issues[0].Milestone = (string)issueData["result"][3]["milestone"]; } issues[0].Owner = (string)issueData["result"][3]["owner"]; issues[0].Type = (string)issueData["result"][3]["type"]; issues[0].Priority = (string)issueData["result"][3]["priority"]; issues[0].Status = (string)issueData["result"][3]["status"]; issues[0].Summary = (string)issueData["result"][3]["summary"]; onData(issues); } } else if (args2.Result[n] == '{') { if (count == 0) { lastObjectStart = n; } ++count; } } } if (onCompleted != null) onCompleted(false, null); }; jsonRPCQuery.WriteArrayEnd(); jsonRPCQuery.WriteObjectEnd(); client2.UploadStringAsync(this.RPCUrl(), jsonRPCQuery.ToString()); if (onProgress != null) client.DownloadProgressChanged += (sender2, args2) => onProgress(args2); } }; if (onProgress != null) client.DownloadProgressChanged += (sender, args) => onProgress(args); var jsonRPCQueryTicktes = new JsonWriter(); jsonRPCQueryTicktes.WriteObjectStart(); jsonRPCQueryTicktes.WritePropertyName("method"); jsonRPCQueryTicktes.Write("ticket.query"); jsonRPCQueryTicktes.WritePropertyName("qstr"); jsonRPCQueryTicktes.Write("status!=closed"); jsonRPCQueryTicktes.WriteObjectEnd(); client.UploadStringAsync(this.RPCUrl(), jsonRPCQueryTicktes.ToString()); return client.CancelAsync; }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Single) { writer.Write((float)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { //If you're getting this error with a Dict<Enum, ...>, that's why. Use string as the key writer.WritePropertyName((string)entry.Key); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName(p_data.Info.Name); WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException(string.Format("Max allowed object depth reached while trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write((string)null); } else if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } } else if (obj is string) { writer.Write((string)obj); } else if (obj is double) { writer.Write((double)obj); } else if (obj is int) { writer.Write((int)obj); } else if (obj is bool) { writer.Write((bool)obj); } else if (obj is long) { writer.Write((long)obj); } else if (obj is Array) { writer.WriteArrayStart(); foreach (object obj2 in (Array)obj) { WriteValue(obj2, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); } else if (obj is IList) { writer.WriteArrayStart(); foreach (object obj3 in (IList)obj) { WriteValue(obj3, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); } else if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { writer.WritePropertyName((string)entry.Key); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); } else { Type key = obj.GetType(); if (custom_exporters_table.ContainsKey(key)) { ExporterFunc func = custom_exporters_table[key]; func(obj, writer); } else if (base_exporters_table.ContainsKey(key)) { ExporterFunc func2 = base_exporters_table[key]; func2(obj, writer); } else if (obj is Enum) { Type underlyingType = Enum.GetUnderlyingType(key); if (((underlyingType == typeof(long)) || (underlyingType == typeof(uint))) || (underlyingType == typeof(ulong))) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } } else { AddTypeProperties(key); IList <PropertyMetadata> list = type_properties[key]; writer.WriteObjectStart(); foreach (PropertyMetadata metadata in list) { if (metadata.IsField) { writer.WritePropertyName(metadata.Info.Name); WriteValue(((FieldInfo)metadata.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo info = (PropertyInfo)metadata.Info; if (info.CanRead) { writer.WritePropertyName(metadata.Info.Name); WriteValue(info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); } } }
public static void serializeInternal(JsonWriter writer, object obj) { // special case if (obj == null) { writer.Write(null); } else if (JsonTypeJuggler.isInt(obj)) { writer.Write((int)(obj)); } else if (JsonTypeJuggler.isLong(obj)) { writer.Write((long)(obj)); } else if (JsonTypeJuggler.isBool(obj)) { writer.Write((bool)(obj)); } else if (JsonTypeJuggler.isString(obj)) { writer.Write((string)(obj)); } else if (JsonTypeJuggler.isDouble(obj)) { writer.Write((double)(obj)); } // array else if (JsonTypeJuggler.isArray(obj)) { writer.WriteArrayStart(); if (JsonTypeJuggler.isInt(obj.GetType().GetElementType())) { int[] array = (int[])obj; for (int i = 0; i < array.Length; i++) { serializeInternal(writer, array[i]); } } else if (JsonTypeJuggler.isLong(obj.GetType().GetElementType())) { long[] array = (long[])obj; for (int i = 0; i < array.Length; i++) { serializeInternal(writer, array[i]); } } else if (JsonTypeJuggler.isBool(obj.GetType().GetElementType())) { bool[] array = (bool[])obj; for (int i = 0; i < array.Length; i++) { serializeInternal(writer, array[i]); } } else if (JsonTypeJuggler.isString(obj.GetType().GetElementType())) { string[] array = (string[])obj; for (int i = 0; i < array.Length; i++) { serializeInternal(writer, array[i]); } } else if (JsonTypeJuggler.isDouble(obj.GetType().GetElementType())) { double[] array = (double[])obj; for (int i = 0; i < array.Length; i++) { serializeInternal(writer, array[i]); } } else { object[] array = (object[])obj; for (int i = 0; i < array.Length; i++) { serializeInternal(writer, array[i]); } } writer.WriteArrayEnd(); } // struct else { writer.WriteObjectStart(); FieldInfo[] fields = obj.GetType().GetFields(); for (int i = 0; i < fields.Length; i++) { writer.WritePropertyName(fields[i].Name); serializeInternal(writer, fields[i].GetValue(obj)); } writer.WriteObjectEnd(); } }
private static void WriteJson(IJsonWrapper wrapper, JsonWriter writer) { if (wrapper == null) { writer.Write(null); return; } if (wrapper.IsString) { writer.Write(wrapper.GetString()); return; } if (wrapper.IsBoolean) { writer.Write(wrapper.GetBoolean()); return; } if (wrapper.IsDouble) { writer.Write(wrapper.GetDouble()); return; } if (wrapper.IsInt) { writer.Write(wrapper.GetInt()); return; } if (wrapper.IsLong) { writer.Write(wrapper.GetLong()); return; } if (wrapper.IsArray) { writer.WriteArrayStart(); foreach (object elem in (IList)wrapper) { WriteJson((JsonData)elem, writer); } writer.WriteArrayEnd(); return; } if (wrapper.IsObject) { if (((IDictionary)wrapper).Count <= 0) { return; } writer.WriteObjectStart(); foreach (DictionaryEntry entry in ((IDictionary)wrapper)) { //TODO: ignore null entry var data = (JsonData)entry.Value; var type = data.GetJsonType(); if (type == JsonType.None) { continue; } if (type == JsonType.Array && ((IList)entry.Value).Count <= 0) { continue; } writer.WritePropertyName((string)entry.Key); WriteJson(data, writer); } writer.WriteObjectEnd(); return; } if (wrapper.GetJsonType() == JsonType.None) { writer.WriteObjectStart(); writer.WriteObjectEnd(); return; } }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { writer.WritePropertyName((string)entry.Key.ToString()); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { // Don't serialize a field or property if if (p_data.Include == false) { continue; } // havoc here 2 if (p_data.IsField) { FieldInfo fInfo = ((FieldInfo)p_data.Info); //Changed: Only write data if field does NOT have the [NonSerialized] Attribute and does NOT have the XmlIgnore Attribute if (fInfo.IsNotSerialized == false //&& !fInfo.GetCustomAttributes(false).Any(a => a is System.Xml.Serialization.XmlIgnoreAttribute) //&& !fInfo.GetCustomAttributes(false).Any(a => a is System.Runtime.Serialization.IgnoreDataMemberAttribute) ) { writer.WritePropertyName(p_data.Info.Name); WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; //Changed: Only write to json if property can be written to // if (p_info.CanRead && p_info.CanWrite // //&& (p_info.GetSetMethod(true) != null && !p_info.GetSetMethod(true).IsPrivate) // //&& !p_info.GetCustomAttributes(false).Any(a => a is System.Xml.Serialization.XmlIgnoreAttribute) // && p_info.GetCustomAttributes(false).Any(a => a is Service.Serializer.Serialize) // ) { if (p_info.CanRead && p_info.CanWrite //&& !p_info.GetCustomAttributes(false).Any(a => a is System.Runtime.Serialization.IgnoreDataMemberAttribute) ) { writer.WritePropertyName(p_data.Info.Name); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); }
private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj == null) { writer.Write(null); return; } if (obj.IsString) { writer.Write(obj.GetString()); return; } if (obj.IsBoolean) { writer.Write(obj.GetBoolean()); return; } if (obj.IsDouble) { writer.Write(obj.GetDouble()); return; } if (obj.IsInt) { writer.Write(obj.GetInt()); return; } if (obj.IsLong) { writer.Write(obj.GetLong()); return; } if (obj.IsArray) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteJson((JsonData)elem, writer); } writer.WriteArrayEnd(); return; } if (obj.IsObject) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in ((IDictionary)obj)) { writer.WritePropertyName((string)entry.Key); WriteJson((JsonData)entry.Value, writer); } writer.WriteObjectEnd(); return; } }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth, bool withTypeInfo = false) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); Type t = obj.GetType().GetElementType(); foreach (object elem in (Array)obj) { currentMemberType = t; WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); Type t = obj.GetType().GetGenericArguments()[0]; foreach (object elem in (IList)obj) { currentMemberType = t; WriteValue(elem, writer, writer_is_private, depth + 1, withTypeInfo); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); Type t = obj.GetType().GetGenericArguments()[1]; foreach (DictionaryEntry entry in (IDictionary)obj) { currentMemberType = t; writer.WritePropertyName((string)entry.Key); WriteValue(entry.Value, writer, writer_is_private, depth + 1, withTypeInfo); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); if (withTypeInfo && currentMemberType != null) { // include typeinfo as string in the serialized object writer.WritePropertyName(keyTypeInfo); // get qualified type name and trim it to contain only the necessary parts(reduce json size) string qualifiedname = obj_type.AssemblyQualifiedName; qualifiedname = rexQualifiedName.Replace(qualifiedname, ""); writer.Write(qualifiedname); } foreach (PropertyMetadata p_data in props) { currentMemberType = null; // Don't serialize a field or property with the JsonIgnore attribute with serialization usage if ((p_data.Ignore & JsonIgnoreWhen.Serializing) > 0) { continue; } if (p_data.IsField) { writer.WritePropertyName(p_data.Info.Name); FieldInfo info = (FieldInfo)p_data.Info; var val = info.GetValue(obj); if (withTypeInfo && val != null) { if (val.GetType().IsSubclassOf(info.FieldType)) { currentMemberType = val.GetType(); Console.WriteLine("write type info for " + currentMemberType); } } WriteValue(val, writer, writer_is_private, depth + 1, withTypeInfo); } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; var val = p_info.GetValue(obj, null); if (withTypeInfo) { if (val != null && val.GetType().IsSubclassOf(p_info.PropertyType)) { currentMemberType = val.GetType(); Console.WriteLine("write type info for " + currentMemberType); } } if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); WriteValue(val, writer, writer_is_private, depth + 1, withTypeInfo); } } } writer.WriteObjectEnd(); }
private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj.IsString) { writer.Write (obj.GetString ()); return; } if (obj.IsBoolean) { writer.Write (obj.GetBoolean ()); return; } if (obj.IsDouble) { writer.Write (obj.GetDouble ()); return; } if (obj.IsInt) { writer.Write (obj.GetInt ()); return; } if (obj.IsLong) { writer.Write (obj.GetLong ()); return; } if (obj.IsArray) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteJson ((JsonData) elem, writer); writer.WriteArrayEnd (); return; } if (obj.IsObject) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in ((IDictionary) obj)) { writer.WritePropertyName ((string) entry.Key); WriteJson ((JsonData) entry.Value, writer); } writer.WriteObjectEnd (); return; } }
private static void WriteJson(JsonData obj, JsonWriter writer) { if (obj == null) { writer.Write(null); return; } switch (obj.GetJsonType()) { case JsonType.String: { writer.Write(((IJsonWrapper)obj).GetString()); return; } case JsonType.Boolean: { writer.Write(((IJsonWrapper)obj).GetBoolean()); return; } case JsonType.Double: { writer.Write(((IJsonWrapper)obj).GetDouble()); return; } case JsonType.Int: { writer.Write(((IJsonWrapper)obj).GetInt()); return; } case JsonType.Long: { writer.Write(((IJsonWrapper)obj).GetLong()); return; } case JsonType.Array: { writer.WriteArrayStart(); int count = obj.EnsureCollection().Count; for (int i = 0; i < count; ++i) { WriteJson((JsonData)((IList)obj)[i], writer); } writer.WriteArrayEnd(); return; } case JsonType.Object: { writer.WriteObjectStart(); foreach (DictionaryEntry entry in ((IDictionary)obj)) { writer.WritePropertyName((string)entry.Key); WriteJson((JsonData)entry.Value, writer); } writer.WriteObjectEnd(); return; } default: return; } }
public void StringBuilderTest() { StringBuilder sb = new StringBuilder (); JsonWriter writer = new JsonWriter (sb); writer.WriteArrayStart (); writer.Write ("like a lizard on a window pane"); writer.WriteArrayEnd (); Assert.AreEqual (sb.ToString (), "[\"like a lizard on a window pane\"]"); }
public static void LitJsonOutputFile () { using (FileStream fs = new FileStream ("litjson_out.txt", FileMode.Create)) { StreamWriter out_stream = new StreamWriter (fs); JsonReader reader = new JsonReader (Common.JsonText); out_stream.WriteLine ("*** Reading with LitJson.JsonReader"); while (reader.Read ()) { out_stream.Write ("Token: {0}", reader.Token); if (reader.Value != null) out_stream.WriteLine (" Value: {0}", reader.Value); else out_stream.WriteLine (""); } out_stream.WriteLine ( "\n*** Writing with LitJson.JsonWriter"); JsonWriter writer = new JsonWriter (out_stream); int n = Common.SampleObject.Length; for (int i = 0; i < n; i += 2) { switch ((char) Common.SampleObject[i]) { case '{': writer.WriteObjectStart (); break; case '}': writer.WriteObjectEnd (); break; case '[': writer.WriteArrayStart (); break; case ']': writer.WriteArrayEnd (); break; case 'P': writer.WritePropertyName ( (string) Common.SampleObject[i + 1]); break; case 'I': writer.Write ( (int) Common.SampleObject[i + 1]); break; case 'D': writer.Write ( (double) Common.SampleObject[i + 1]); break; case 'S': writer.Write ( (string) Common.SampleObject[i + 1]); break; case 'B': writer.Write ( (bool) Common.SampleObject[i + 1]); break; case 'N': writer.Write (null); break; } } out_stream.WriteLine ( "\n\n*** Data imported with " + "LitJson.JsonMapper\n"); Person art = JsonMapper.ToObject<Person> (Common.PersonJson); out_stream.Write (art.ToString ()); out_stream.WriteLine ( "\n\n*** Object exported with " + "LitJson.JsonMapper\n"); out_stream.Write (JsonMapper.ToJson (Common.SamplePerson)); out_stream.WriteLine ( "\n\n*** Generic object exported with " + "LitJson.JsonMapper\n"); JsonData person = JsonMapper.ToObject (Common.PersonJson); out_stream.Write (JsonMapper.ToJson (person)); out_stream.WriteLine ( "\n\n*** Hashtable exported with " + "LitJson.JsonMapper\n"); out_stream.Write (JsonMapper.ToJson (Common.HashtablePerson)); out_stream.Close (); } }
public void NullTest() { JsonWriter writer = new JsonWriter (); writer.WriteArrayStart (); writer.Write (null); writer.WriteArrayEnd (); }
public void LoadWidgets(bool exclude_unless_post) { Debug.Assert(m_setup_complete, "You must call SetupComplete() before LoadWidgets()"); if (m_widgets_loaded) return; // already loaded - presumably by SetupComplete() m_widgets_loaded = true; // make request to backend to get widget HTML JsonWriter w = new JsonWriter(); w.WriteObjectStart(); w.WritePropertyName("modules"); w.WriteArrayStart(); foreach (RemoteWidget wi in m_widgets.Values) { if (exclude_unless_post && wi.Method == "get") continue; wi.DumpJson(w); } w.WriteArrayEnd(); // modules w.WritePropertyName("global"); w.WriteObjectStart(); w.WritePropertyName("language"); w.Write(m_language); if (m_have_user) { w.WritePropertyName("user"); w.WriteObjectStart(); w.WritePropertyName("namespace"); w.Write(m_user_namespace); w.WritePropertyName("id"); w.Write(m_user_id); w.WritePropertyName("login"); w.Write(m_user_login); w.WritePropertyName("email"); w.Write(m_user_email); w.WritePropertyName("url"); w.Write(m_user_url); w.WritePropertyName("first_name"); w.Write(m_user_first_name); w.WritePropertyName("last_name"); w.Write(m_user_last_name); w.WritePropertyName("thumbnail_url"); w.Write(m_user_thumbnail_url); w.WriteObjectEnd(); // user } w.WritePropertyName("items"); w.WriteArrayStart(); foreach (RemoteWidgetSubject s in m_items) { w.WriteObjectStart(); foreach (string k in s.Keys) { w.WritePropertyName(k); object v = s[k]; if (v is int) w.Write((int)v); else if (v is string) w.Write((string)v); else throw new Exception("RemoteWidgetSubject values must be ints or strings"); } w.WriteObjectEnd(); } w.WriteArrayEnd(); w.WriteObjectEnd(); // global w.WriteObjectEnd(); // outer string json_request = w.ToString(); // now post the request to the backend server HttpWebRequest req = (HttpWebRequest)WebRequest.Create(m_remote_url); req.Method = "POST"; req.ContentType = "application/x-javascript"; byte[] post_data = Encoding.UTF8.GetBytes(json_request); req.ContentLength = post_data.Length; string raw_data = ""; try { Stream post_stream = req.GetRequestStream(); post_stream.Write(post_data, 0, post_data.Length); post_stream.Close(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader resp_stream = new StreamReader(resp.GetResponseStream()); /* while (true) { string line = resp_stream.ReadLine(); if (line == null) break; Debug.Print("line from response: " + line); } */ raw_data = resp_stream.ReadToEnd(); resp.Close(); } catch (WebException e) { SetError("Error communicating with widget server: " + e.Message); return; } try { JsonData data = JsonMapper.ToObject(raw_data); // http request done - now handle the json response if (((IDictionary)data).Contains("error")) { SetError((string)data["error"]); return; } JsonData modules = data["modules"]; if (!modules.IsArray) { SetError("JSON server returned non-array for modules."); return; } foreach (JsonData module in modules) { string module_id = module["id"].ToString(); RemoteWidget wi = (RemoteWidget)m_widgets[module_id]; wi.LoadFromJson(module); } } catch (JsonException) { SetError("BAD JSON RESPONSE FROM WIDGET SERVER: " + raw_data); return; } }
public void NumbersTest() { JsonWriter writer = new JsonWriter (); writer.WriteArrayStart (); writer.Write (0); writer.Write (100); writer.Write ((byte) 200); writer.Write (-256); writer.Write (10000000000l); writer.Write ((decimal) 0.333); writer.Write ((float) 0.0001); writer.Write (9e-20); writer.Write (2.3e8); writer.Write (Math.PI); writer.WriteArrayEnd (); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth, bool IgnoreField = false) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1, IgnoreField); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteValue(elem, writer, writer_is_private, depth + 1, IgnoreField); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { //to do writer.WritePropertyName((String)entry.Key); WriteValue(entry.Value, writer, writer_is_private, depth + 1, IgnoreField); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { if (IgnoreField) { continue; } writer.WritePropertyName(p_data.Info.Name); WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1, IgnoreField); } else { PropertyInfo p_info = (PropertyInfo)p_data.Info; if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1, IgnoreField); } } } if (obj is System.Dynamic.ExpandoObject) { IDictionary <string, object> dict = obj as IDictionary <string, object>; int n = dict.Keys.Count; IEnumerator <String> enumerable = dict.Keys.GetEnumerator(); while (enumerable.MoveNext()) { writer.WritePropertyName(enumerable.Current); WriteValue(dict[enumerable.Current], writer, writer_is_private, depth + 1, IgnoreField); } } writer.WriteObjectEnd(); }
private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj == null) { writer.Write((string)null); } else if (obj.IsString) { writer.Write(obj.GetString()); } else if (obj.IsBoolean) { writer.Write(obj.GetBoolean()); } else if (obj.IsDouble) { writer.Write(obj.GetDouble()); } else if (obj.IsInt) { writer.Write(obj.GetInt()); } else if (obj.IsLong) { writer.Write(obj.GetLong()); } else if (obj.IsArray) { writer.WriteArrayStart(); IEnumerator enumerator = obj.GetEnumerator(); try { while (enumerator.MoveNext()) { object current = enumerator.Current; WriteJson((JsonData)current, writer); } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable == null) { } disposable.Dispose(); } writer.WriteArrayEnd(); } else if (obj.IsObject) { writer.WriteObjectStart(); IDictionaryEnumerator enumerator2 = obj.GetEnumerator(); try { while (enumerator2.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)enumerator2.Current; writer.WritePropertyName((string)entry.Key); WriteJson((JsonData)entry.Value, writer); } } finally { IDisposable disposable2 = enumerator2 as IDisposable; if (disposable2 == null) { } disposable2.Dispose(); } writer.WriteObjectEnd(); } }
private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj.IsString) { writer.Write(obj.GetString()); return; } if (obj.IsBoolean) { writer.Write(obj.GetBoolean()); return; } if (obj.IsDouble) { writer.Write(obj.GetDouble()); return; } if (obj.IsInt) { writer.Write(obj.GetInt()); return; } if (obj.IsLong) { writer.Write(obj.GetLong()); return; } if (obj.IsArray) { writer.WriteArrayStart(); { // foreach(var elem in (IList) obj) var __enumerator3 = ((IList)obj).GetEnumerator(); while (__enumerator3.MoveNext()) { var elem = (object)__enumerator3.Current; WriteJson((JsonData)elem, writer); } } writer.WriteArrayEnd(); return; } if (obj.IsObject) { writer.WriteObjectStart(); { // foreach(var entry in ((IDictionary) obj)) var __enumerator4 = (((IDictionary)obj)).GetEnumerator(); while (__enumerator4.MoveNext()) { var entry = (DictionaryEntry)__enumerator4.Current; { writer.WritePropertyName((string)entry.Key); WriteJson((JsonData)entry.Value, writer); } } } writer.WriteObjectEnd(); return; } }
public void StringsTest() { JsonWriter writer = new JsonWriter (); writer.WriteArrayStart (); writer.Write ("Hello World!"); writer.Write ("\n\r\b\f\t"); writer.Write ("I \u2665 you"); writer.Write ("She said, \"I know what it's like to be dead\""); writer.WriteArrayEnd (); }
public void LoadWidgets(bool exclude_unless_post) { Debug.Assert(m_setup_complete, "You must call SetupComplete() before LoadWidgets()"); if (m_widgets_loaded) return; // already loaded - presumably by SetupComplete() m_widgets_loaded = true; // make request to backend to get widget HTML JsonWriter w = new JsonWriter(); w.WriteObjectStart(); w.WritePropertyName("modules"); w.WriteArrayStart(); foreach (RemoteWidget wi in m_widgets.Values) { if (exclude_unless_post && wi.Method == "get") continue; wi.DumpJson(w); } w.WriteArrayEnd(); // modules w.WritePropertyName("global"); w.WriteObjectStart(); w.WritePropertyName("user"); w.WriteObjectStart(); w.WritePropertyName("namespace"); w.Write(m_user_namespace); w.WritePropertyName("user_id"); w.Write(m_user_id); // placeholder for now until we get shadow accounts working w.WritePropertyName("email"); w.Write(m_user_email); w.WritePropertyName("first_name"); w.Write(m_user_first_name); w.WritePropertyName("last_name"); w.Write(m_user_last_name); w.WriteObjectEnd(); // user w.WriteObjectEnd(); // global w.WriteObjectEnd(); // outer string json_request = w.ToString(); // now post the request to the backend server HttpWebRequest req = (HttpWebRequest)WebRequest.Create(m_remote_url); req.Method = "POST"; req.ContentType = "application/x-javascript"; byte[] post_data = Encoding.UTF8.GetBytes(json_request); req.ContentLength = post_data.Length; Stream post_stream = req.GetRequestStream(); post_stream.Write(post_data, 0, post_data.Length); post_stream.Close(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader resp_stream = new StreamReader(resp.GetResponseStream()); /* while (true) { string line = resp_stream.ReadLine(); if (line == null) break; Debug.Print("line from response: " + line); } */ string raw_data = resp_stream.ReadToEnd(); resp.Close(); string error = null; try { JsonData data = JsonMapper.ToObject(raw_data); // http request done - now handle the json response if (((IDictionary)data).Contains("error")) { error = (string)data["error"]; } else { JsonData modules = data["modules"]; if (!modules.IsArray) error = "JSON server returned non-array for modules."; else foreach (JsonData module in modules) { string module_id = module["id"].ToString(); RemoteWidget wi = (RemoteWidget)m_widgets[module_id]; wi.LoadFromJson(module); } } } catch (JsonException) { error = "BAD JSON RESPONSE FROM WIDGET SERVER: " + raw_data; } if (error != null) { foreach (RemoteWidget wi in m_widgets.Values) { wi.HTML = m_page.Server.HtmlEncode(error); } } }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } Type obj_type; if (obj is ILRuntime.Runtime.Intepreter.ILTypeInstance) { obj_type = ((ILRuntime.Runtime.Intepreter.ILTypeInstance)obj).Type.ReflectionType; } else if (obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType) { obj_type = ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)obj).ILInstance.Type.ReflectionType; } else { obj_type = obj.GetType(); } // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write((( IJsonWrapper )obj).ToJson()); } else { (( IJsonWrapper )obj).ToJson(writer); } return; } if (obj is String) { writer.Write(( string )obj); return; } if (obj is Double) { writer.Write(( double )obj); return; } if (obj is Single) { writer.Write(( float )obj); return; } if (obj is Int32) { writer.Write(( int )obj); return; } if (obj is Boolean) { writer.Write(( bool )obj); return; } if (obj is Int64) { writer.Write(( long )obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in ( Array )obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in ( IList )obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary dictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in dictionary) { var propertyName = entry.Key is string key ? key : Convert.ToString(entry.Key, CultureInfo.InvariantCulture); writer.WritePropertyName(propertyName); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType(obj_type); if (e_type == typeof(long) || e_type == typeof(uint) || e_type == typeof(ulong)) { writer.Write(( ulong )obj); } else { writer.Write(( int )obj); } return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName(p_data.Info.Name); WriteValue((( FieldInfo )p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = ( PropertyInfo )p_data.Info; if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) { throw new JsonException( String.Format("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is String) { writer.Write((string)obj); return; } if (obj is Double) { writer.Write((double)obj); return; } if (obj is Int32) { writer.Write((int)obj); return; } if (obj is Boolean) { writer.Write((bool)obj); return; } if (obj is Int64) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); foreach (object elem in (Array)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) { WriteValue(elem, writer, writer_is_private, depth + 1); } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in (IDictionary)obj) { writer.WritePropertyName((string)entry.Key); WriteValue(entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd(); return; } Type obj_type = obj.GetType(); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter(obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey(obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter(obj, writer); return; } // It looks like the input should be exported as an object AddTypeProperties(obj_type); IList <PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart(); foreach (PropertyMetadata p_data in props) { writer.WritePropertyName(p_data.Info.Name); if (p_data.IsField) { WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { WriteValue(((PropertyInfo)p_data.Info).GetValue( obj, null), writer, writer_is_private, depth + 1); } } writer.WriteObjectEnd(); }
private static void WriteValue(object obj, JsonWriter writer, bool privateWriter, int depth) { if (depth > maxNestingDepth) { throw new JsonException(string.Format("Max allowed object depth reached while trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (privateWriter) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is string) { writer.Write((string)obj); return; } if (obj is double) { writer.Write((double)obj); return; } if (obj is long) { writer.Write((long)obj); return; } if (obj is bool) { writer.Write((bool)obj); return; } if (obj is Array) { writer.WriteArrayStart(); Array arr = (Array)obj; Type elemType = arr.GetType().GetElementType(); foreach (object elem in arr) { // if the collection contains polymorphic elements, we need to include type information for deserialization if (writer.TypeHinting && elem != null && elem.GetType() != elemType) { writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(elem.GetType().FullName); writer.WritePropertyName(writer.HintValueName); WriteValue(elem, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(elem, writer, privateWriter, depth + 1); } } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); IList list = (IList)obj; // collection might be non-generic type like Arraylist Type elemType = typeof(object); if (list.GetType().GetGenericArguments().Length > 0) { // collection is a generic type like List<T> elemType = list.GetType().GetGenericArguments()[0]; } foreach (object elem in list) { // if the collection contains polymorphic elements, we need to include type information for deserialization if (writer.TypeHinting && elem != null && elem.GetType() != elemType) { writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(elem.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(elem, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(elem, writer, privateWriter, depth + 1); } } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); IDictionary dict = (IDictionary)obj; // collection might be non-generic type like Hashtable Type elemType = typeof(object); if (dict.GetType().GetGenericArguments().Length > 1) { // collection is a generic type like Dictionary<T, V> elemType = dict.GetType().GetGenericArguments()[1]; } foreach (DictionaryEntry entry in dict) { writer.WritePropertyName((string)entry.Key); // if the collection contains polymorphic elements, we need to include type information for deserialization if (writer.TypeHinting && entry.Value != null && entry.Value.GetType() != elemType) { writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(entry.Value.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(entry.Value, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(entry.Value, writer, privateWriter, depth + 1); } } writer.WriteObjectEnd(); return; } Type objType = obj.GetType(); // Try a base or custom importer if one exists ExporterFunc exporter = GetExporter(objType); if (exporter != null) { exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type enumType = Enum.GetUnderlyingType(objType); if (enumType == typeof(long)) { writer.Write((long)obj); } else { ExporterFunc enumConverter = GetExporter(enumType); if (enumConverter != null) { enumConverter(obj, writer); } } return; } // Okay, it looks like the input should be exported as an object ObjectMetadata tdata = AddObjectMetadata(objType); writer.WriteObjectStart(); foreach (string property in tdata.Properties.Keys) { PropertyMetadata pdata = tdata.Properties[property]; // Don't serialize soft aliases (which get added to ObjectMetadata.Properties twice). if (pdata.Alias != null && property != pdata.Info.Name && tdata.Properties.ContainsKey(pdata.Info.Name)) { continue; } // Don't serialize a field or property with the JsonIgnore attribute with serialization usage if ((pdata.Ignore & JsonIgnoreWhen.Serializing) > 0) { continue; } if (pdata.IsField) { FieldInfo info = (FieldInfo)pdata.Info; if (pdata.Alias != null) { writer.WritePropertyName(pdata.Alias); } else { writer.WritePropertyName(info.Name); } object value = info.GetValue(obj); if (writer.TypeHinting && value != null && info.FieldType != value.GetType()) { // the object stored in the field might be a different type that what was declared, need type hinting writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(value.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(value, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(value, writer, privateWriter, depth + 1); } } else { PropertyInfo info = (PropertyInfo)pdata.Info; if (info.CanRead) { if (pdata.Alias != null) { writer.WritePropertyName(pdata.Alias); } else { writer.WritePropertyName(info.Name); } object value = info.GetValue(obj, null); if (writer.TypeHinting && value != null && info.PropertyType != value.GetType()) { // the object stored in the property might be a different type that what was declared, need type hinting writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(value.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(value, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(value, writer, privateWriter, depth + 1); } } } } writer.WriteObjectEnd(); }
private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > JsonMapper.max_nesting_depth) { throw new JsonException(string.Format("Max allowed object depth reached while trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (writer_is_private) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is string) { writer.Write((string)obj); return; } if (obj is double) { writer.Write((double)obj); return; } if (obj is float) { writer.Write((double)((float)obj)); return; } if (obj is int) { writer.Write((int)obj); return; } if (obj is bool) { writer.Write((bool)obj); return; } if (obj is long) { writer.Write((long)obj); return; } if (obj is Array) { writer.WriteArrayStart(); IEnumerator enumerator = ((Array)obj).GetEnumerator(); try { while (enumerator.MoveNext()) { object obj2 = enumerator.Current; JsonMapper.WriteValue(obj2, writer, writer_is_private, depth + 1); } } finally { IDisposable disposable; if ((disposable = (enumerator as IDisposable)) != null) { disposable.Dispose(); } } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); IEnumerator enumerator2 = ((IList)obj).GetEnumerator(); try { while (enumerator2.MoveNext()) { object obj3 = enumerator2.Current; JsonMapper.WriteValue(obj3, writer, writer_is_private, depth + 1); } } finally { IDisposable disposable2; if ((disposable2 = (enumerator2 as IDisposable)) != null) { disposable2.Dispose(); } } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); IDictionaryEnumerator enumerator3 = ((IDictionary)obj).GetEnumerator(); try { while (enumerator3.MoveNext()) { object obj4 = enumerator3.Current; DictionaryEntry dictionaryEntry = (DictionaryEntry)obj4; writer.WritePropertyName((string)dictionaryEntry.Key); JsonMapper.WriteValue(dictionaryEntry.Value, writer, writer_is_private, depth + 1); } } finally { IDisposable disposable3; if ((disposable3 = (enumerator3 as IDisposable)) != null) { disposable3.Dispose(); } } writer.WriteObjectEnd(); return; } Type type = obj.GetType(); if (JsonMapper.custom_exporters_table.ContainsKey(type)) { ExporterFunc exporterFunc = JsonMapper.custom_exporters_table[type]; exporterFunc(obj, writer); return; } if (JsonMapper.base_exporters_table.ContainsKey(type)) { ExporterFunc exporterFunc2 = JsonMapper.base_exporters_table[type]; exporterFunc2(obj, writer); return; } if (obj is Enum) { Type underlyingType = Enum.GetUnderlyingType(type); if (underlyingType == typeof(long) || underlyingType == typeof(uint) || underlyingType == typeof(ulong)) { writer.Write((ulong)obj); } else { writer.Write((int)obj); } return; } JsonMapper.AddTypeProperties(type); IList <PropertyMetadata> list = JsonMapper.type_properties[type]; writer.WriteObjectStart(); foreach (PropertyMetadata propertyMetadata in list) { if (propertyMetadata.IsField) { writer.WritePropertyName(propertyMetadata.Info.Name); JsonMapper.WriteValue(((FieldInfo)propertyMetadata.Info).GetValue(obj), writer, writer_is_private, depth + 1); } else { PropertyInfo propertyInfo = (PropertyInfo)propertyMetadata.Info; if (propertyInfo.CanRead) { writer.WritePropertyName(propertyMetadata.Info.Name); JsonMapper.WriteValue(propertyInfo.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd(); }
public static string GetSchedule(IDbConnection db) { TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); long today = (long)t.TotalSeconds; StringBuilder sb = new StringBuilder(); LitJson.JsonWriter writer = new LitJson.JsonWriter(sb); writer.WriteObjectStart(); writer.WritePropertyName("bookings"); writer.WriteArrayStart(); using (IDbCommand command = db.CreateCommand()) { command.CommandText = "select id, day, [from], till, _user, _meetingroom, users_notified, users_to_be_notified, users_checkedin from booking where day>= @Day order by day, [from]"; IDbDataParameter p = command.CreateParameter(); p.ParameterName = "@Day"; p.Value = today; command.Parameters.Add(p); using (IDataReader reader = command.ExecuteReader()) { while (reader.Read()) { new MeetingRoomBooking(reader).Write(writer); } } } writer.WriteArrayEnd(); writer.WritePropertyName("rooms"); writer.WriteObjectStart(); List<MeetingRoom> MeetingRooms = new List<MeetingRoom>(); MeetingRooms = MeetingRoom.List(db); foreach (MeetingRoom meetingRoom in MeetingRooms) { writer.WritePropertyName(meetingRoom.Id.ToString()); meetingRoom.Write(writer); } writer.WriteObjectEnd(); writer.WritePropertyName("users"); writer.WriteObjectStart(); List<User> Users = new List<User>(); Users = User.list(db); foreach (User user in Users) { writer.WritePropertyName(user.Email); user.Write(writer); } writer.WriteObjectEnd(); writer.WriteObjectEnd(); return sb.ToString(); }
public void StringsTest () { JsonWriter writer = new JsonWriter (); writer.WriteArrayStart (); writer.Write ("Hello World!"); writer.Write ("\n\r\b\f\t"); writer.Write ("I \u2665 you"); writer.Write ("She said, \"I know what it's like to be dead\""); writer.WriteArrayEnd (); string json = "[\"Hello World!\",\"\\n\\r\\b\\f\\t\",\"I \\u2665 you\"" + ",\"She said, \\\"I know what it's like to be dead\\\"\"]"; Assert.AreEqual (json, writer.ToString(), "A1"); }