如何使用C#解析JSON数组

时间:2015-03-03 20:09:29

标签: c# arrays json parsing

已经检查了这篇文章,但这并没有解决我的情况:Parsing a JSON array using Json.Net

我有一个API响应,它返回一个JSON数组,如下所示:

{
    "status": {
        "code": "200",
        "description": "OK"
    },
    "response": [{
        "weId": "1",
        "weName": "env1"
    },{
        "weId": "2",
        "weName": "env2"
    },{
        "weId": "3",
        "weName": "env3"
    }]
}

这是我的问题:

此数组可能返回2个以上的值。

我的意思是这样的:

{
    "response": [{
        "weId": "1",
        "weName": "env1",
        "otherAttribute1": "otherValue1",
        "otherAttribute2": "otherValue2",
        "otherAttribute3": "otherValue3"
    }]
}

我如何动态解析具有未知维度的JSON数组?

提前致谢。

1 个答案:

答案 0 :(得分:3)

Json.Net可以动态解析为JObject

var unParsed = @"{
    ""response"": [{
        ""weId"": ""1"",
        ""weName"": ""env1"",
        ""otherAttribute1"": ""otherValue1"",
        ""otherAttribute2"": ""otherValue2"",
        ""otherAttribute3"": ""otherValue3""
    }]
}";

dynamic d = JObject.Parse(unParsed);
Console.WriteLine(d.response[0].weId);
Console.WriteLine(d.response[0].otherAttribute1);

foreach (var r in d.response)
{
    foreach (var prop in r.Properties())
    {
        Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
    }
}

现在,话虽如此,您可能不需要动态地执行此操作。如果你有一组已知的可选参数,你可以将它反序列化为强类型对象,任何缺失的东西都只是默认值(0表示int,null表示类等),如下面的答案所示:

public static void JsonParsing()
{
    var unParsed = @"{
        ""status"": {
            ""code"": ""200"",
            ""description"": ""OK""
        },
        ""response"": [{
            ""weId"": ""1"",
            ""weName"": ""env1""
        },{
            ""weId"": ""2"",
            ""weName"": ""env2"",
            ""otherAttribute1"": ""value1"",
            ""otherAttribute2"": ""value2"",
            ""otherAttribute3"": ""value3""
        },{
            ""weId"": ""3"",
            ""weName"": ""env3""
        }]
    }";

    var parsed = JsonConvert.DeserializeObject<Rootobject>(unParsed);
    Console.WriteLine(parsed.Response[0].OtherAttribute1); // writes a "" since it's null
    Console.WriteLine(parsed.Response[1].OtherAttribute1); // writes "Value1"
    Console.WriteLine(parsed);
}