Json反序列化为List

时间:2011-09-20 01:22:31

标签: c# json

我正在编写一个Windows Phone应用程序,它将从服务器获取一组数据并在列表框中显示每个条目。

数据来自服务器,看起来像这样

{
  "data": [
    {
      "value1": 777103069782066, 
      "value2": "SomeString", 
      "value3": "TextToDisplay1"
    }, 
    {
      "value1": 750050696652932, 
      "value2": "SomeString2", 
      "value3": "TextToDisplay2"
    }, 
    {
      "value1": 516092242936133, 
      "value2": "SomeString3", 
      "value3": "TextToDisplay3"
    } 
  ]
}

我知道如何将数据放入像这样的字典

Dictionary<string, object> values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

但是它将它全部集成到一个字典条目中(可以预料,这就是全部)。

我想获取“data”中的所有列表项并将它们存储在变量testList中 - 所以我可以从'testList'访问每个单独的字典。我怎么能这样做?

很抱歉,如果这个问题有点罗嗦。如果需要,我可以澄清。

谢谢,
克里斯

1 个答案:

答案 0 :(得分:0)

为什么不创建自己的数据类:

public class MyClass
{
    public long value1;
    public string value2;
    public string value3;
}

然后像这样反序列化:

Dictionary<string, IEnumerable<MyClass>> values = JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<MyClass>>>(json);

IEnumerable<MyClass>部分将是testList

UPD :如果您想避免自定义对象使用类似

的内容
Dictionary<string, IEnumerable<Dictionary<string, string>>> values = 
    JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<Dictionary<string, string>>>>(json);
相关问题