使用[JsonConvert()]时,JSON.Net抛出StackOverflowException

时间:2015-04-18 15:51:45

标签: c# json serialization json.net

我将这个简单的代码编写为Serialize类为flatten,但是当我使用[JsonConverter(typeof(FJson))]注释时,它会抛出 StackOverflowException 。如果我手动调用SerializeObject,它可以正常工作。

如何在注释模式下使用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();
        }

        public override bool CanConvert(Type objectType)
        {
            return true; // works for any type
        }
    }

6 个答案:

答案 0 :(得分:5)

Json.NET对于调用JToken.FromObject生成"默认"的转换器没有方便的支持。序列化,然后修改生成的JToken输出 - 正是因为您观察到的StackOverflowException将发生。

一种解决方法是使用线程静态布尔值在递归调用中临时禁用转换器。使用线程静态是因为在某些情况下(包括),JSON转换器的实例将在线程之间共享。在这种情况下,通过实例属性禁用转换器将不是线程安全的。

public class FJson : JsonConverter
{
    [ThreadStatic]
    static bool disabled;

    // Disables the converter in a thread-safe manner.
    bool Disabled { get { return disabled; } set { disabled = value; } }

    public override bool CanWrite { get { return !Disabled; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken t;
        using (new PushValue<bool>(true, () => Disabled, (canWrite) => Disabled = canWrite))
        {
            t = JToken.FromObject(value, serializer);
        }

        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();
    }

    public override bool CanConvert(Type objectType)
    {
        return true; // works for any type
    }
}

public struct PushValue<T> : IDisposable
{
    Func<T> getValue;
    Action<T> setValue;
    T oldValue;

    public PushValue(T value, Func<T> getValue, Action<T> setValue)
    {
        if (getValue == null || setValue == null)
            throw new ArgumentNullException();
        this.getValue = getValue;
        this.setValue = setValue;
        this.oldValue = getValue();
        setValue(value);
    }

    #region IDisposable Members

    // By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
    public void Dispose()
    {
        if (setValue != null)
            setValue(oldValue);
    }

    #endregion
}

注意这个转换器只写;阅读没有实现。

顺便提一下,您编写的转换器会创建具有重复名称的JSON:

{
  "id": 1,
  "name": null,
  "name": "value"
}

这虽然不是严格违法,但通常被认为是bad practice

如果您确定您的转换器不会跨线程共享,您可以改为使用成员变量:

public class FJson : JsonConverter
{
    bool CannotWrite { get; set; }

    public override bool CanWrite { get { return !CannotWrite; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken t;
        using (new PushValue<bool>(true, () => CannotWrite, (canWrite) => CannotWrite = canWrite))
        {
            t = JToken.FromObject(value, serializer);
        }

        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();
    }

    public override bool CanConvert(Type objectType)
    {
        return true; // works for any type
    }
}

在此方案中,必须调用JToken.FromObject(Object, JsonSerializer)并传递传入的序列化程序,以便使用转换器FJson的相同实例。完成此操作后,您可以将[JsonConverter(typeof(FJson))]还原到您的班级A

[JsonConverter(typeof(FJson))]
public class A
{
}

答案 1 :(得分:5)

阅读(并测试)Paul Kiar&amp; p.kaneman解决方案我说实施WriteJson似乎是一项具有挑战性的任务。即使它适用于大多数情况 - 有一些尚未涵盖的边缘情况。 例子:

  • public bool ShouldSerialize*()种方法
  • null
  • 值类型(struct
  • json converter attributes
  • ..

这是(只是)另一次尝试:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
    if (ReferenceEquals(value, null)) {
        writer.WriteNull();
        return;
    }

    var contract = (JsonObjectContract)serializer
        .ContractResolver
        .ResolveContract(value.GetType());

    writer.WriteStartObject();

    foreach (var property in contract.Properties) {
        if (property.Ignored) continue;
        if (!ShouldSerialize(property, value)) continue;

        var property_name = property.PropertyName;
        var property_value = property.ValueProvider.GetValue(value);

        writer.WritePropertyName(property_name);
        if (property.Converter != null && property.Converter.CanWrite) {
            property.Converter.WriteJson(writer, property_value, serializer);
        } else {
            serializer.Serialize(writer, property_value);
        }
    }

    writer.WriteEndObject();
}

private static bool ShouldSerialize(JsonProperty property, object instance) {
    return property.ShouldSerialize == null 
        || property.ShouldSerialize(instance);
}

答案 2 :(得分:4)

我不喜欢上面发布的解决方案,所以我弄清楚序列化程序如何实际序列化对象并试图将其提取到最低限度:

public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
{
   JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract( value.GetType() );

   writer.WriteStartObject();
   foreach ( var property in contract.Properties )
   {
      writer.WritePropertyName( property.PropertyName );
      writer.WriteValue( property.ValueProvider.GetValue(value));
   }
   writer.WriteEndObject();
}

没有堆栈溢出问题,也不需要递归禁用标志。

答案 3 :(得分:2)

我还不能发表评论,很抱歉......但我只想在Paul Kiar提供的解决方案中加入一些内容。他的解决方案真的帮助了我。

保罗的代码简短,只需在没有任何自定义对象构建的情况下工作。 我想要做的唯一补充是插入一个检查属性是否被忽略。如果将其设置为忽略,则跳过该属性的写入:

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(value.GetType());

        writer.WriteStartObject();
        foreach (var property in contract.Properties)
        {
            if (property.Ignored)
                continue;

            writer.WritePropertyName(property.PropertyName);
            writer.WriteValue(property.ValueProvider.GetValue(value));
        }
        writer.WriteEndObject();
    }

答案 4 :(得分:1)

通过将属性放在类A上,它将被递归调用。 WriteJson覆盖的第一行再次调用A类的序列化器。

JToken t = JToken.FromObject(value);

这会导致递归调用,从而导致StackOverflowException。

从您的代码中,我认为您正试图压扁层面。您可以通过将转换器属性放在属性B上来实现此目的,这将避免递归。

//remove the converter from here
public class A
{
    public A()
    {
        this.b = new B();
    }

    public int id { get; set; }
    public string name { get; set; }
    [JsonConverter(typeof(FJson))] 
    public B b { get; set; }
}

警告:你到这里的Json将有两个名为&#34; name &#34;一个来自A班,另一个来自B班。

答案 5 :(得分:0)

可以使用以下事实来生成应用了JsonConverter的类型的默认序列化:应用到成员的转换器取代了应用到类型,或在设置中。来自docs

  

使用JsonConverter的优先级是由成员上的属性定义的JsonConverter,然后是由类上的属性定义的JsonConverter,最后是传递给JsonSerializer的所有转换器。

因此,可以通过将其嵌套在具有单个成员的DTO中并将其嵌套在类型实例中并应用dummy converter的方式来为您的类型生成默认序列化,除了回到读和写的默认序列化。

以下扩展方法和转换器可以完成工作:

public static class JsonExtensions
{
    public static JToken DefaultFromObject(this JsonSerializer serializer, object value)
    {
        if (value == null)
            return JValue.CreateNull();
        var dto = Activator.CreateInstance(typeof(DefaultSerializationDTO<>).MakeGenericType(value.GetType()), value);
        var root = JObject.FromObject(dto, serializer);
        return root["Value"].RemoveFromLowestPossibleParent() ?? JValue.CreateNull();
    }

    public static JToken RemoveFromLowestPossibleParent(this JToken node)
    {
        if (node == null)
            return null;
        // If the parent is a JProperty, remove that instead of the token itself.
        var contained = node.Parent is JProperty ? node.Parent : node;
        contained.Remove();
        // Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should
        if (contained is JProperty)
            ((JProperty)node.Parent).Value = null;
        return node;
    }

    [JsonObject(NamingStrategyType = typeof(DefaultNamingStrategy), IsReference = false)]
    class DefaultSerializationDTO<T>
    {
        public DefaultSerializationDTO() { }

        public DefaultSerializationDTO(T value) { this.Value = value; }

        [JsonConverter(typeof(NoConverter)), JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Serialize)]
        public T Value { get; set; }
    }
}

public class NoConverter : JsonConverter
{
    // NoConverter taken from this answer https://stackoverflow.com/a/39739105/3744182
    // To https://stackoverflow.com/questions/39738714/selectively-use-default-json-converter
    // By https://stackoverflow.com/users/3744182/dbc
    public override bool CanConvert(Type objectType)  { throw new NotImplementedException(); /* This converter should only be applied via attributes */ }

    public override bool CanRead { get { return false; } }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); }

    public override bool CanWrite { get { return false; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); }
}

然后按如下所示在FJson.WriteJson()中使用它:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    JToken t = serializer.DefaultFromObject(value);
    // Remainder as before
    if (t.Type != JTokenType.Object)
    {
        t.WriteTo(writer);
        return;
    }

    JObject o = (JObject)t;
    writer.WriteStartObject();
    WriteJson(writer, o);
    writer.WriteEndObject();
}

此解决方案的优点是:

  1. 它不依赖于递归禁用转换器,因此可以与递归数据模型一起正常工作。

  2. 不需要重新实现从对象属性序列化对象的整个逻辑。

演示小提琴here