public string Encode(object obj) { JsonWriter writer = new JsonWriter(); JsonMapper.ToJson(obj, writer); return writer.ToString(); }
//[MenuItem("Editors/LiumkTest/123123")] static void ShowEditor() { //EditorUtility.DisplayDialog("MyTool", "Do It in C# !", "OK", ""); if (s_instance == null) { //Type[] types = new Type[2] { typeof(BlackWood.NodeCanvas.Editor.SkinContainer), typeof(BlackWood.NodeCanvas.Editor.BBPContainer) }; //s_instance = GetWindow<ZEditor>("Unit Browser", true, types); s_instance = GetWindow <ZEditor>(false, "ZEditor"); } //s_instance.Show(); s_instance.Show(); var testObject = new ObjectTest(); var writer = new LitJson.JsonWriter { PrettyPrint = true }; LitJson.JsonMapper.ToJson(testObject, writer); string path = "./Assets/test.json"; if (File.Exists(path)) { File.Delete(path); } File.WriteAllText(path, writer.ToString(), Encoding.UTF8); }
public static string JsonPrettyFormat(this string json) { LitJson.JsonWriter writer1 = new LitJson.JsonWriter(); writer1.PrettyPrint = true; writer1.IndentValue = 4; LitJson.JsonMapper.ToJson(MiniJSON.Json.Deserialize(json), writer1); return(writer1.ToString()); }
public static string ToString(object obj, bool prettyPrint) { var writer = new LitJson.JsonWriter { PrettyPrint = prettyPrint }; LitJson.JsonMapper.ToJson(obj, writer); return(writer.ToString()); }
public void SaveTasks(TaskList.SerializedForm serializedForm) { JsonWriter writer = new JsonWriter(); writer.PrettyPrint = true; JsonMapper.ToJson(serializedForm, writer); string json = writer.ToString(); StreamWriter sr = new StreamWriter(this.taskFile); sr.Write(json); sr.Close(); }
public void SaveSettings(Settings.SerializedForm serializedForm) { JsonWriter writer = new JsonWriter(); writer.PrettyPrint = true; JsonMapper.ToJson(serializedForm, writer); string json = writer.ToString(); StreamWriter sr = new StreamWriter(this.configFile); sr.Write(json); sr.Close(); }
private void saveCellMapSetting() { var writer = new LitJson.JsonWriter { PrettyPrint = true }; LitJson.JsonMapper.ToJson(m_curMapConfig, writer); File.WriteAllText(mt_curFilePath, writer.ToString()); Repaint(); }
/// <summary> /// 输出符合文本可视化的Json /// </summary> /// <param name="obj"></param> public static string ToPrettyJson(object obj) { lock (_prettyJsonWriter) { _prettyJsonWriter.Reset(); if (false == _prettyJsonWriter.PrettyPrint) { _prettyJsonWriter.IndentValue = 4; _prettyJsonWriter.PrettyPrint = true; } WriteValue(obj, _prettyJsonWriter, true, 0); var json = _prettyJsonWriter.ToString(); //解决中文为正则表达式的问题 json = System.Text.RegularExpressions.Regex.Unescape(json); return(json); } }
void _TestSerialInfo() { SerialInfo v1 = new SerialInfo(); v1.vector2 = new Vector2(0.5f, 0.5f); if (m_Format == Format.Pretty) { m_PrettyWriter.Reset(); LitJson.JsonMapper.ToJson(v1, m_PrettyWriter); m_str1 = m_PrettyWriter.ToString(); } else { m_str1 = LitJson.JsonMapper.ToJson(v1); //serialize object to string } LitJson.JsonMapper.ToObject <SerialInfo>(m_str1); //de-serialize string back to object }
public static string ToJson(object obj, bool isformat = false) { if (isformat) { var jw = new JsonWriter() { IndentValue = 2, PrettyPrint = true }; ToJson(obj, jw); return(jw.ToString()); } lock (static_writer_lock) { static_writer.Reset(); WriteValue(obj, static_writer, true, 0); return(static_writer.ToString()); } }
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); }
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 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); }
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); }
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 ExportPrettyPrint() { OrderedDictionary sample = new OrderedDictionary (); sample["rolling"] = "stones"; sample["flaming"] = "pie"; sample["nine"] = 9; string expected = @" { ""rolling"" : ""stones"", ""flaming"" : ""pie"", ""nine"" : 9 }"; JsonWriter writer = new JsonWriter (); writer.PrettyPrint = true; JsonMapper.ToJson (sample, writer); Assert.AreEqual (expected, writer.ToString (), "A1"); writer.Reset (); writer.IndentValue = 8; expected = @" { ""rolling"" : ""stones"", ""flaming"" : ""pie"", ""nine"" : 9 }"; JsonMapper.ToJson (sample, writer); Assert.AreEqual (expected, writer.ToString (), "A2"); }
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 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 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; } }
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 static string ToJson(object obj, JsonWriter writer) { WriteValue(obj, writer, false, 0); return(writer.ToString()); }
public static string Serialize() { var dto = new MusicDTO.EditData(); dto.BPM = EditData.BPM.Value; dto.maxBlock = EditData.MaxBlock.Value; dto.offset = EditData.OffsetSamples.Value; dto.name = Path.GetFileNameWithoutExtension(EditData.Name.Value); var sortedNoteObjects = EditData.Notes.Values .Where(note => !(note.note.type == NoteTypes.Long && EditData.Notes.ContainsKey(note.note.prev))) .OrderBy(note => note.note.position.ToSamples(Audio.Source.clip.frequency, EditData.BPM.Value)); dto.notes = new List<MusicDTO.Note>(); foreach (var noteObject in sortedNoteObjects) { if (noteObject.note.type == NoteTypes.Single) { dto.notes.Add(ToDTO(noteObject)); } else if (noteObject.note.type == NoteTypes.Long) { var current = noteObject; var note = ToDTO(noteObject); while (EditData.Notes.ContainsKey(current.note.next)) { var nextObj = EditData.Notes[current.note.next]; note.notes.Add(ToDTO(nextObj)); current = nextObj; } dto.notes.Add(note); } } var jsonWriter = new JsonWriter(); jsonWriter.PrettyPrint = true; jsonWriter.IndentValue = 4; JsonMapper.ToJson(dto, jsonWriter); return jsonWriter.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}{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 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()); }
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); } } }
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"); }