如何在Json.Net中将动态序列化和反序列化为IDictionary <string,object>

时间:2016-11-19 17:28:19

标签: c# json.net

我必须使用早于4.5.2的旧版Json.Net(我们的ESB使用它)。

基于DynamicObject的类存在内存泄漏。

我正在使用Rick的Expando课程https://github.com/RickStrahl/Expando

我想将我的Expando对象序列化为IDictionary并将其反序列化为我的Expando对象

我试图使用CustomJsonConverter,如你所见:

public class ExpandoConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(Expando).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        JObject jObject = JObject.Load(reader);
        // It is easier to write readJson I will implement
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var x = (value as Expando);
        writer.WriteStartObject();
        foreach (var item in x.GetProperties(true))
        {
            writer.WritePropertyName(item.Key);

            serializer.Serialize(writer,item.Value);

            writer.WriteEndObject();
        }
        writer.WriteEndObject();
    }

但每次我尝试实现WriteJson时,我都会遇到奇怪的错误:

  

Token PropertyName in state Array would result in an invalid JSON object. Path '$values'.

有没有这样简单的方法(在WriteJson中):

 var dictionary= ExpandoToDictionary(expando);
 serializer.Serialize(writer,dictionary);

1 个答案:

答案 0 :(得分:1)

如果没有mcve,您的代码可能会出现其他问题,但您需要从WriteEndObject()删除对WriteJson()的内部调用:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    var x = (value as Expando);
    writer.WriteStartObject();
    foreach (var item in x.GetProperties(true))
    {
        writer.WritePropertyName(item.Key);

        serializer.Serialize(writer,item.Value);

        // Do not close the object here also.
    }
    writer.WriteEndObject();
}

应拨打WriteStartObject()WriteEndObject()的电话。