1

我从如下所示的 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 响应的“报告”部分的正确方法是什么?

4

2 回答 2

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());
于 2013-03-18T16:47:20.810 回答
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; } 
   }
于 2013-03-15T22:29:43.760 回答