简体   繁体   English

C#参考早期的JSON元素-Newtonsoft

[英]C# Reference earlier JSON element - Newtonsoft

I'm serializing an object which has a List<X> and a Dictionary<X, Y> . 我正在序列化具有List<X>Dictionary<X, Y>

The List<X> is serializing without any issues. List<X>正在序列化,没有任何问题。 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. 问题是我不知道如何在转换器中引用List<X> 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. 假设JSON是线性反序列化的,那么List<X>应该已经反序列化了,但是由于DeserializeObject()方法尚未完成,因此我对此没有任何引用。

How would I go about solving this? 我将如何解决这个问题?

My solution in the end was to change the way I stored 'X'. 最后,我的解决方案是更改存储“ X”的方式。 Instead of storing the keys of the dictionary as keys in the json, I stored each keyvaluepair as an array item. 我没有将字典的键存储为json中的键,而是将每个键值对存储为数组项。

Each item then is: { "key": { "$ref" : 5 } "value": { "$ref" : 10 } } 每个项目然后是: { "key": { "$ref" : 5 } "value": { "$ref" : 10 } }

For writing, this was just a matter of using JArray , JObject and JToken.FromObject (making sure to pass in the serializer. 对于编写,这只是使用JArrayJObjectJToken.FromObject (确保传递序列化器。

For reading, jObject.GetValue("Key").ToObject<X>(serializer) worked brilliantly. 为了阅读, jObject.GetValue("Key").ToObject<X>(serializer)表现出色。

Hope this helps someone. 希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM