将JSON字符串反序列化为C#中的嵌套类?

时间:2013-03-15 21:48:27

标签: c# json deserialization

我从HTTP请求中收到一个JSON字符串,如下所示:

[
   {
  "size":590,
  "location":"California",
  "report":{
     "Bob":[
        null,
        "12.0.250.0",
        "20130228"
     ],
     "Mary":[
        null,
        "2013-02-28.01",
        "20130228"
     ],
     "John":[
        null,
        "12.00",
        "59123805"
     ]
  }
},
{
  "size":12348,
  "location":"Florida",
  "report":{
     "Misty":[
        null,
        "65492.592",
        "89216753"
     ],
     "Billy":[
        null,
        "789208.w9",
        "65320880"
     ],
     "John":[
        null,
        "89.8056",
        "75920889"
     ]
   }
 }
]

我正在尝试反序列化的类的结构如下:

[DataContract]
public class DeserializedObject
{
    [DataMember(Name = "size")]
    public UInt64 Size { get; set; }

    [DataMember(Name = "location")]
    public string Location { get; set; }

    [DataMember(Name = "report")]
    public Dictionary<string, ReportData> Report { get; set; } 
}

[CollectionDataContract]
public class ReportData : List<object>
{
    public string a
    {
        get { return (string)this[0]; }
        set { this[0] = (string)value; }
    }

    public string b
    {
        get { return (string)this[1]; }
        set { this[1] = (string)value; }
    }

    public string c
    {
        get { return (string)this[2]; }
        set { this[2] = (string)value; }
    }
}

当我尝试反序列化时,报告始终为空。

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<DeserializedObject>));
List<DeserializedObject> list = serializer.ReadObject(stream) as List<DeserializedObject>;

反序列化JSON响应的“报告”部分的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

问题是您的报告类未正确设置。 json.NET正在寻找密钥a,b和c。除此之外,字典中的值是字符串数组,而不是对象。 ReportData一个对象。这种不匹配是造成错误的原因。

我认为报告应该只是从项目中删除类型<string, string[]>ReportData的字典。如果我这样做,我将使用以下类(实际上不需要DataContract的东西);

  public class DeserializedObject
  {
      public UInt64 size { get; set; }

       public string location { get; set; }

       public Dictionary<string, string[]> report { get; set; } 
   }

答案 1 :(得分:0)

我能够使用Json.NET成功反序列化JSON字符串。我用来反序列化字符串的类看起来像这样:

[DataContract]
public class DeserializedObject
{
    [DataMember(Name = "size")]
    public UInt64 Size { get; set; }

    [DataMember(Name = "location")]
    public string Location { get; set; }

    [DataMember(Name = "report")]
    public Dictionary<string, string[]> Report { get; set; } 
}

用于反序列化对象的代码如下所示:

StreamReader reader = new StreamReader(stream);
List<DeserializedObject> instance = JsonConvert.DeserializeObject<List<DeserializedObject>>(reader.ReadToEnd());