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 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); }
private void SerializeTable(SerializeTable table, LitJson.JsonWriter writer) { if (0 == table.KeyValueMap.Count && 0 == table.Children.Count) { return; } writer.WritePropertyName(table.Name); writer.WriteObjectStart(); using (Dictionary <string, SerializeTable.Value> .Enumerator next = table.KeyValueMap.GetEnumerator()) { while (next.MoveNext()) { writer.WritePropertyName(next.Current.Key); //writer.Write(next.Current.Value.obj); WriteValue(next.Current.Value.obj, writer, 0); } } foreach (SerializeTable node in table.Children) { SerializeTable(node, writer); } writer.WriteObjectEnd(); }
/// <summary> /// 将一场战斗序列化到路径... /// </summary> /// <param name="outputPath"></param> private void SerializeBattleFieldToPath(string outputPath) { string folderPath = Path.GetDirectoryName(outputPath); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } using (TextWriter tw = new StreamWriter(outputPath)) { LitJson.JsonWriter jsonWriter = new LitJson.JsonWriter(tw); #if UNITY_EDITOR //弄得好看一点 jsonWriter.PrettyPrint = true; #endif jsonWriter.WriteObjectStart(); { //序列化战斗 jsonWriter.WriteObject("battleField", battleField); } jsonWriter.WriteObjectEnd(); Debug.LogFormat("序列化战场完毕 => {0}", outputPath); System.Diagnostics.Process.Start("explorer.exe", folderPath); } }
public void ErrorArrayClosingTest() { JsonWriter writer = new JsonWriter (); writer.WriteArrayStart (); writer.Write (true); writer.WriteObjectEnd (); }
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 static void WriteIntField(this LitJson.JsonWriter writer, string propertyName, Vector2 value) { propertyName = propertyName.Replace(".", "#"); writer.WritePropertyName(propertyName); writer.WriteObjectStart(); writer.WriteField("x", (int)value.x); writer.WriteField("y", (int)value.y); writer.WriteObjectEnd(); }
public override void OnSerializeTable(SerializeTable rootTable) { writer = new JsonWriter(stream); writer.PrettyPrint = PrettyPrint; writer.WriteObjectStart(); SerializeTable(rootTable, writer); writer.WriteObjectEnd(); }
public static void WriteField(this LitJson.JsonWriter writer, string propertyName, Quaternion value) { propertyName = propertyName.Replace(".", "#"); writer.WritePropertyName(propertyName); writer.WriteObjectStart(); writer.WriteField("x", value.eulerAngles.x); writer.WriteField("y", value.eulerAngles.y); writer.WriteField("z", value.eulerAngles.z); writer.WriteObjectEnd(); }
public static string generateReadParamJson() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); JsonWriter writer = new JsonWriter(sb); writer.WriteObjectStart(); writer.WritePropertyName("action"); writer.Write("get"); writer.WritePropertyName("id"); writer.Write("SC9008637"); writer.WritePropertyName("page"); writer.Write("channel_param"); writer.WriteObjectEnd(); return sb.ToString(); }
public static Boolean AddJsonProperty(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.WriteObjectStart(); jw.WritePropertyName(name); jw.Write(""); jw.WriteObjectEnd(); targetjsondata = JsonMapper.ToObject(sb.ToString()); 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(); }
private JsonData JngsSgyParser(JsonData jsobj) { JsonData jret = null; JsonBase jbr = null; if (jsobj != null) { #region 统一代码 try { if (jsobj != null) { string optaction = "mobile_BLL.Interface." + jsobj["optstring"].ToString() + ",mobile_BLL"; Type type = Type.GetType(optaction); jbr = (JsonBase)Activator.CreateInstance(type, jsobj["optdata"]); } if (jbr != null) { jbr.strBaseUrl = HttpContext.Current.Request.Url.AbsoluteUri; jbr.strBaseUrl = jbr.strBaseUrl.Replace(HttpContext.Current.Request.Url.AbsolutePath, ""); jbr.strBaseUrl += HttpContext.Current.Request.ApplicationPath; StringBuilder sb = new StringBuilder(); LitJson.JsonWriter jw = new LitJson.JsonWriter(sb); jw.WriteObjectStart(); jw.WritePropertyName("result"); jw.Write(""); jw.WriteObjectEnd(); jret = JsonMapper.ToObject(sb.ToString()); jret["result"] = (JsonData)jbr.GetData(); } } catch (Exception ex) { BaseDal.RecordError("json数据返回出错_get_data.ashx", ex.ToString()); } #endregion } return(jret); }
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 static bool SaveProject(bool add, ProjectBuildData data) { DataRow drProject = null; DataTable dt = LoadAndCreateProjects(PROJECTS_CONFIG_FILE); foreach (DataRow dr in dt.Rows) { string name = dr["ProjectName"].ToString(); if (name == data.Name) { drProject = dr; break; } } if (add && drProject != null) { Debug.LogError("exist same project name already " + data.Name); return(false); } else if (!add && drProject == null) { Debug.LogError("project not exist " + data.Name); return(false); } else if (add) { drProject = dt.NewRow(); dt.Rows.Add(drProject); } drProject["ProjectName"] = data.Name; drProject["Version"] = data.Version; List <string> sceneList = new List <string>(); foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes) { if (!scene.enabled) { continue; } sceneList.Add(scene.path); } string scenes = string.Join(";", sceneList.ToArray()); drProject["Scenes"] = scenes; drProject["Target"] = EditorUserBuildSettings.activeBuildTarget; drProject["SymbolDefine"] = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); drProject["DebugBuild"] = EditorUserBuildSettings.development.ToString(); FieldInfo[] optionFields = typeof(GameOptions).GetFields(); foreach (var field in optionFields) { if (!field.IsPublic || field.IsStatic) { continue; } if (!dt.Columns.Contains(field.Name)) { dt.Columns.Add(field.Name); } var obj = field.GetValue(data.Options); if (obj != null) { if (field.FieldType == typeof(string) || field.FieldType == typeof(bool) || field.FieldType == typeof(int) || field.FieldType.IsEnum) { drProject[field.Name] = obj.ToString(); } else if (field.FieldType.IsGenericType) { drProject[field.Name] = LitJson.JsonMapper.ToJson(obj); } } } PropertyInfo[] fields = typeof(PlayerSettings).GetProperties(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { if (!field.CanWrite) { continue; } var obj = field.GetValue(null, null); if (obj != null) { drProject[field.Name] = obj.ToString(); if (field.PropertyType == typeof(Texture2D)) { var texture = obj as Texture2D; drProject[field.Name] = texture.name; } } } var types = typeof(PlayerSettings).GetNestedTypes(); foreach (var type in types) { var sb = new StringBuilder(); var writer = new LitJson.JsonWriter(sb); writer.WriteObjectStart(); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Static); foreach (var property in properties) { if (!property.CanWrite) { continue; } writer.WritePropertyName(property.Name); var obj = property.GetValue(null, null); writer.Write(obj != null ? obj.ToString() : ""); } writer.WriteObjectEnd(); if (!drProject.Table.Columns.Contains(type.Name)) { drProject.Table.Columns.Add(type.Name); } drProject[type.Name] = sb.ToString(); } var iconList = new List <string>(); var group = GetBuildGroupByTarget(data.Target); var icons = PlayerSettings.GetIconsForTargetGroup(group); foreach (var texture2D in icons) { if (texture2D != null) { var path = AssetDatabase.GetAssetPath(texture2D.GetInstanceID()); iconList.Add(path); } } var iconsStr = string.Join(",", iconList.ToArray()); drProject["Icons"] = iconsStr; if (data.Games != null) { var str = LitJson.JsonMapper.ToJson(data.Games); drProject["Games"] = str; } SaveToDB(dt, PROJECTS_CONFIG_FILE); //SaveConfig(data); return(true); }
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(); }
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(); }
public void ErrorPropertyExpectedTest() { JsonWriter writer = new JsonWriter (); writer.WriteObjectStart (); writer.Write (10); writer.WriteObjectEnd (); }
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 NestedObjectsTest() { JsonWriter writer = new JsonWriter (); string json = "{\"book\":{\"title\":" + "\"Structure and Interpretation of Computer Programs\"," + "\"details\":{\"pages\":657}}}"; writer.WriteObjectStart (); writer.WritePropertyName ("book"); writer.WriteObjectStart (); writer.WritePropertyName ("title"); writer.Write ( "Structure and Interpretation of Computer Programs"); writer.WritePropertyName ("details"); writer.WriteObjectStart (); writer.WritePropertyName ("pages"); writer.Write (657); writer.WriteObjectEnd (); writer.WriteObjectEnd (); writer.WriteObjectEnd (); 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; } 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 (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 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; }
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()); }
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 (); }
protected static void WriteRequest(string id, string method, ApiParamsWriterDelegate parameters, StreamWriter sw) { JsonWriter writer = new JsonWriter(sw); writer.WriteObjectStart(); writer.WritePropertyName("id"); writer.Write(id); writer.WritePropertyName("method"); writer.Write(method); writer.WritePropertyName("params"); if (parameters == null) writer.Write(null); else parameters(writer); writer.WriteObjectEnd(); }
public void CreateStomt(bool negative, string target, string text) { StringBuilder json = new StringBuilder(); LitJson.JsonWriter writer = new LitJson.JsonWriter(json); writer.WriteObjectStart(); writer.WritePropertyName("anonym"); writer.Write(true); writer.WritePropertyName("negative"); writer.Write(negative); writer.WritePropertyName("target_id"); writer.Write(target); writer.WritePropertyName("text"); writer.Write(text); writer.WriteObjectEnd(); StartCoroutine(CreateStomtAsync(json.ToString())); }
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(); }
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 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 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; } } }
public void ObjectTest() { JsonWriter writer = new JsonWriter (); string json = "{\"flavour\":\"strawberry\",\"color\":\"red\"," + "\"amount\":3}"; writer.WriteObjectStart (); writer.WritePropertyName ("flavour"); writer.Write ("strawberry"); writer.WritePropertyName ("color"); writer.Write ("red"); writer.WritePropertyName ("amount"); writer.Write (3); writer.WriteObjectEnd (); Assert.AreEqual (writer.ToString (), json); }
public void WriteResponse(string id, Response resp, Exception error, StreamWriter sw) { JsonWriter writer = new JsonWriter(sw); writer.WriteObjectStart(); writer.WritePropertyName("id"); writer.Write(id); if (error == null) { writer.WritePropertyName("error"); writer.Write(null); writer.WritePropertyName("result"); if (resp == null) writer.Write(null); else resp.Write(writer, false); } else { writer.WritePropertyName("result"); writer.Write(null); writer.WritePropertyName("error"); writer.Write(string.Format("{0}\n{1}", error.Message, error.StackTrace.ToString())); } 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(); }
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(); } }
public void ErrorValueExpectedTest() { JsonWriter writer = new JsonWriter (); writer.WriteObjectStart (); writer.WritePropertyName ("foo"); writer.WriteObjectEnd (); }
public void DumpJson(JsonWriter w) { w.WriteObjectStart(); w.WritePropertyName("id"); w.Write(m_module_id); w.WritePropertyName("name"); w.Write(m_module_name); w.WritePropertyName("method"); w.Write(m_method); w.WritePropertyName("ajax_url"); w.Write(m_ajax_url); w.WritePropertyName("post_url"); w.Write(m_post_url); w.WritePropertyName("param_prefix"); w.Write(m_param_prefix); w.WritePropertyName("args"); w.WriteNameValueCollection(m_args); w.WritePropertyName("params"); w.WriteNameValueCollection(m_params); w.WriteObjectEnd(); }
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 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 Report(string category, JsonWriter json, bool logFailure) { json.WriteObjectEnd(); try { string gameKey, secretKey; GetKeys(out gameKey, out secretKey); string jsonMessage = json.ToString(); string url = GetApiUrl(gameKey, category); string auth = GetAuthorization(jsonMessage, secretKey); string result = Post(url, jsonMessage, auth); MyTrace.Send(TraceWindow.Analytics, jsonMessage); } catch (Exception ex) { m_enabled = false; if (logFailure) { // Do not write it to log as classic exception (it would also make false reports for error reporter) MySandboxGame.Log.WriteLine("Sending analytics failed: " + ex.Message); } } }
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(); }
public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; // Validate incoming request if (request.HttpMethod != "POST") { response.StatusCode = 405; response.StatusDescription = "Method not allowed"; response.End(); return; } if (request.Headers["X-Nuntiuz-Service-Key"] != sikey) { response.StatusCode = 401; response.StatusDescription = "Not authorized"; response.End(); return; } if (!request.ContentType.StartsWith("application/json-rpc")) { response.StatusCode = 400; response.StatusDescription = "Bad request"; response.End(); return; } string id = null; string method = null; IDictionary<string, object> parameters = null; // parse request with culter en-US for safe JSON parsing CultureInfo serverCulture = Thread.CurrentThread.CurrentCulture; CultureInfo usCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = usCulture; try { try { IDictionary<String, object> jsonRpcData = ReadJsonRpcData(request.InputStream); id = (string)jsonRpcData["id"]; method = (string)jsonRpcData["method"]; parameters = (IDictionary<string, object>)jsonRpcData["parameters"]; } catch (Exception e) { using (StreamWriter sw = new StreamWriter(response.OutputStream)) { JsonWriter writer = new JsonWriter(sw); writer.WriteObjectStart(); writer.WritePropertyName("id"); writer.Write(id); writer.WritePropertyName("result"); writer.Write(null); writer.WritePropertyName("error"); writer.Write(string.Format("{0}\n{1}", e.Message, e.StackTrace.ToString())); writer.WriteObjectEnd(); } response.ContentType = "application/json-rpc"; response.StatusCode = 200; response.End(); return; } } finally { Thread.CurrentThread.CurrentCulture = serverCulture; } Exception error = null; Response resp = null; try { resp = ExecuteMethod(method, parameters); } catch (Exception exception) { error = exception; } Thread.CurrentThread.CurrentCulture = usCulture; try { using (StreamWriter sw = new StreamWriter(response.OutputStream)) { WriteResponse(id, resp, error, sw); } } finally { Thread.CurrentThread.CurrentCulture = serverCulture; } response.ContentType = "application/json-rpc"; response.StatusCode = 200; response.End(); }
public string ToJson() { var jsWriter = new JsonWriter(); jsWriter.WriteObjectStart(); jsWriter.WritePropertyName("alg"); jsWriter.Write(Algorithm.ToString()); if (null != KeyUri) { switch (KeyFormat) { case KeyFormat.Json: jsWriter.WritePropertyName("jku"); break; case KeyFormat.X509: jsWriter.WritePropertyName("xku"); break; case KeyFormat.Rfc4050: jsWriter.WritePropertyName("xdu"); break; } jsWriter.Write(KeyUri.ToString()); } if (false == string.IsNullOrEmpty(KeyId)) { jsWriter.WritePropertyName("kid"); jsWriter.Write(KeyId); } jsWriter.WriteObjectEnd(); return jsWriter.ToString(); }
private static void serializeCallbackResult(JsonWriter writer, CallbackResult result) { if (result == null) { writer.Write(null); } else { writer.WriteObjectStart(); writer.WritePropertyName("type"); if (result is FlowCallbackResult) writer.Write("flow"); else if (result is MessageCallbackResult) writer.Write("message"); else if (result is FormCallbackResult) writer.Write("form"); writer.WritePropertyName("value"); result.Write(writer, false); 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 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 UNITY_2018_3_OR_NEWER if (obj is IDictionary dictionary) { #else if (obj is IDictionary) { var dictionary = obj as IDictionary; #endif writer.WriteObjectStart(); foreach (DictionaryEntry entry in dictionary) { #if UNITY_2018_3_OR_NEWER var propertyName = entry.Key is string key ? key : Convert.ToString(entry.Key, CultureInfo.InvariantCulture); #else var propertyName = entry.Key is string?(entry.Key as string) : Convert.ToString(entry.Key, CultureInfo.InvariantCulture); #endif writer.WritePropertyName(propertyName); 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) { var skipAttributesList = p_data.Info.GetCustomAttributes(typeof(JsonIgnore), true); var skipAttributes = skipAttributesList as ICollection <Attribute>; if (skipAttributes.Count > 0) { continue; } 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(); }