C# Reference earlier JSON element - Newtonsoft

时间:2017-10-12 09:43:51

标签: c# json serialization

I'm serializing an object which has a List<X> and a Dictionary<X, Y>.

The List<X> is serializing without any issues. To serialize the dictionary however, I've implemented a custom converter.

class XYDictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(Dictionary<X, Y>).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);

        Dictionary<X, Y> dictionary = new Dictionary<X, Y>();

        foreach (JProperty property in jObject.Properties())
        {
            X key = //Get Y using property.Name

            if (key != null)
            {
                dictionary.Add(key, property.Value.ToObject<Y>());
            }
        }

        return dictionary;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        IDictionary<X, Y> dictionary = (IDictionary<X, Y>)value;

        JObject jObject = new JObject();

        foreach (var kvp in dictionary)
        {
            jObject.Add(kvp.Key.name, kvp.Value == null ? null : JToken.FromObject(kvp.Value));
        }

        jObject.WriteTo(writer);
    }
}

The problem is that I have no idea how to reference the List<X> within the converter. Assuming the JSON is deserialized linearly, the List<X> should have been deserialized by this point, but as the DeserializeObject() method hasn't finished yet, I don't have any reference to it.

How would I go about solving this?

1 个答案:

答案 0 :(得分:0)

我的解决方案最终是改变我存储的方式&#39; X&#39;。 我没有将字典的键存储为json中的键,而是将每个keyvaluepair存储为数组项。

每个项目都是:{ "key": { "$ref" : 5 } "value": { "$ref" : 10 } }

对于写作,这只是使用JArrayJObjectJToken.FromObject的问题(确保传入序列化程序。

为了阅读,jObject.GetValue("Key").ToObject<X>(serializer)工作得非常出色。

希望这有助于某人。