使用动态属性名称反序列化json

时间:2018-12-05 22:31:54

标签: json json.net json-deserialization

此处Serialize/Deserialize dynamic property name using JSON.NET提出了类似的问题。我无法使其在以下情况下正常工作:

我有以下JSON

{
    "notes": {
        "data": [{
                "book": {
                    "items": [{
                            "page": "page 1",
                            "comment": "Some notes"
                        },
                        {
                            "page": "page 1",
                            "comment": "Some notes"
                        }
                    ]
                }
            },
            {
                "journal": {
                    "items": [{
                            "page": "page 1",
                            "comment": "Some notes"
                        },
                        {
                            "page": "page 1",
                            "comment": "Some notes"
                        }
                    ]
                }
            },
            {
                "magazine": {
                    "items": [{
                            "page": "page 1",
                            "comment": "Some notes"
                        },
                        {
                            "page": "page 1",
                            "comment": "Some notes"
                        }
                    ]
                }
            }
        ]
    }
}

创建了以下用于JSON序列化的类:

public class TestParse
  {
    public Note Notes { get; set; }
  }
  public class Note
  {
    public IList<Data> Data { get; set; }
  }

  public class Data
  {
    public Source Source { get; set; }
  }

  [JsonConverter(typeof(MyConverter))]
  public class Source
  {
    public IList<Items> Items { get; set; }
  }

  public class Items
  {
    public string Page { get; set; }
    public string Comment { get; set; }
  }

  public class MyConverter : JsonConverter
  {
    public override bool CanConvert(Type objectType)
    {
      return objectType == typeof(Source);
    }

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

      var req = new Data
      {
        Source = jo.ToObject<Source>()
      };
      return req;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      var req = (Source)value;
      var jo = new JObject(
          new JObject(req.Items));
      jo.WriteTo(writer);
    }
  }
}

我仍然无法反序列化“源”。任何指针表示赞赏。

1 个答案:

答案 0 :(得分:1)

在您引用的other question中,动态键由同一对象中另一个属性的值确定。因此,需要转换器。

在您的情况下,您具有动态键,但是它们不依赖任何东西。 您这里真的不需要转换器。您可以只使用字典来处理动态键。

在您的Note类中更改此行:

public IList<Data> Data { get; set; }

对此:

public IList<IDictionary<string, Source>> Data { get; set; }

,然后从您的[JsonConverter]类中删除Source属性。那就可以了。
(您也可以删除Data类,因为它不是必需的。)

提琴:https://dotnetfiddle.net/80lIRI