如何从反序列化的JSON对象中获取值?

时间:2015-02-06 19:58:56

标签: c# json

我尝试导入JSON,解析它并能够在整个应用中使用它。例如,我想循环并能够打印出岁月。我该怎么做呢?

代码

var result = await content.ReadAsStringAsync ();

try 
{
    List<RootObject> list = (List<RootObject>)JsonConvert.DeserializeObject<List<RootObject>>(result);

}

catch (Exception e) {
    Console.WriteLine (e);
}

JSON

{
    "ROWCOUNT": 3,
    "COLUMNS": [
        "YEARMFG",
        "MAKE",
        "MODEL",
        "ENGINE",
        "TOWLIMIT",
        "NOTE1",
        "NOTE2"
    ],
    "DATA": {
        "YEARMFG": [
            2012,
            2012,
            2012
        ],
        "MAKE": [
            "Chevrolet/GMC",
            "Chevrolet/GMC",
            "Chevrolet/GMC"
        ],
        "MODEL": [
            "Avalanche 1500 4WD",
            "Avalanche 1500 4WD",
            "Avalanche 1500 4WD"
        ],
        "ENGINE": [
            "5.3L V-8",
            "5.3L V-8",
            "5.3L V-8"
        ],
        "TOWLIMIT": [
            5000,
            5500,
            8000
        ],
        "NOTE1": [
            "3.08 axle ratio",
            "3.42 axle ratio",
            "3.42 axle ratio"
        ],
        "NOTE2": [
            "",
            "",
            "Cooling or other accessory package required "
        ]
    }
}

类:

public class DATA
{
    public List<int> YEARMFG { get; set; }
    public List<string> MAKE { get; set; }
    public List<string> MODEL { get; set; }
    public List<string> ENGINE { get; set; }
    public List<int> TOWLIMIT { get; set; }
    public List<string> NOTE1 { get; set; }
    public List<string> NOTE2 { get; set; }
}

public class RootObject
{
    public int ROWCOUNT { get; set; }
    public List<string> COLUMNS { get; set; }
    public DATA DATA { get; set; }
}

2 个答案:

答案 0 :(得分:4)

假设您的对象和GetJson()只返回JSON字符串:

var obj = JsonConvert.DeserializeObject<RootObject>(GetJSON());
foreach (var year in obj.DATA.YEARMFG)
{
    Console.WriteLine("Year: {0}", year);
}

哪个应输出(基于您的样本数据):

Year: 2012
Year: 2012
Year: 2012

附注:您不必反序列化为List<RootObject>RootObject应该是一个单独的实体(因为它包装了您的整个JSON数据)。因此,只需将其反序列化为单个实例,然后访问DATA属性并迭代YEARMFG

答案 1 :(得分:0)

您要对List<RootObject>进行反序列化,因此List中的每个元素都是RootObject。您可以在班级中看到RootObject具有DATA属性,其中包含List<string> YEARMFG

您应该能够访问list中的项目,如下所示:

list.DATA.YEARMFG会为您提供给定项目的年份列表。

如果您想单独显示它们,可以遍历列表:

foreach (var yr in list.DATA.YEARMFG)
{
    // handle individual year info here
}