对每个键值反序列化具有不同对象类型的JSON文件

时间:2016-05-06 03:35:05

标签: c# json serialization json.net deserialization

我有一个像这样的json对象

{
  "UrbanSourceUnsealedRoad": 
  [
    {
      "Name": "Baseflow Total Nitrogen Standard Deviation (log mg/L)",
      "Min": "1",
      "Max": "2",
      "Default": "3",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    {
      "Name": "Stormflow Total Nitrogen Mean (log mg/L)",
      "Min": "4",
      "Max": "5",
      "Default": "6",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    ...
  ],
  "UrbanSourceSealedRoad": 
  [
    {
      "Name": "Baseflow Total Nitrogen Standard Deviation (log mg/L)",
      "Min": "1",
      "Max": "2",
      "Default": "3",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    {
      "Name": "Stormflow Total Nitrogen Mean (log mg/L)",
      "Min": "4",
      "Max": "5",
      "Default": "6",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    ...
  ],
  ...
}

我已使用C#

中的JSON.net对此进行了反序列化
JsonConvert.DeserializeObject<Dictionary<string, List<ParameterInfo>>>(json)

这很好用,但是现在我想更改json,使其在文件顶部包含一个额外的字段。

即:

{
    "UrbanLandUse" : ["UrbanSourceMixed", "UrbanSourceSealedRoad", "UrbanSourceUnsealedRoad" ], 
    "UrbanSourceUnsealedRoad": 
    [
        { 
        ...

但现在我的json文件不再是包含List<ParameterInfo>

的字典

JSON Spec似乎表明它确实可能

但我不确定如何使用JSON.net API反序列化它

我可以这样做吗?

1 个答案:

答案 0 :(得分:1)

准备一个包含ParameterInfo的包含对象和所需的新对象。 像这样:

public class Container
{
    public Dictionary<string, List<ParameterInfo>> {get; set;}
    public string[] UrbanLandUse {get; set;}
}

然后像这样反序列化到该对象:

JsonConvert.DeserializeObject<Container>(json);

让我知道这是否有效。