我將這些簡(jiǎn)單的代碼寫為Serialize類,以使其扁平化,但是當(dāng)我使用[JsonConverter(typeof(FJson))]批注時(shí),它將引發(fā)StackOverflowException。如果我SerializeObject手動(dòng)撥打電話,它可以正常工作。如何在注釋模式下使用JsonConvert:class Program { static void Main(string[] args) { A a = new A(); a.id = 1; a.b.name = "value"; string json = null; // json = JsonConvert.SerializeObject(a, new FJson()); without [JsonConverter(typeof(FJson))] annotation workd fine // json = JsonConvert.SerializeObject(a); StackOverflowException Console.WriteLine(json); Console.ReadLine(); } } //[JsonConverter(typeof(FJson))] StackOverflowException public class A { public A() { this.b = new B(); } public int id { get; set; } public string name { get; set; } public B b { get; set; } } public class B { public string name { get; set; } } public class FJson : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { JToken t = JToken.FromObject(value); if (t.Type != JTokenType.Object) { t.WriteTo(writer); return; } JObject o = (JObject)t; writer.WriteStartObject(); WriteJson(writer, o); writer.WriteEndObject(); } private void WriteJson(JsonWriter writer, JObject value) { foreach (var p in value.Properties()) { if (p.Value is JObject) WriteJson(writer, (JObject)p.Value); else p.WriteTo(writer); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); }
使用[JsonConvert()]時(shí),JSON.Net引發(fā)StackOverflow
慕運(yùn)維8079593
2019-12-06 10:54:00