解析动态json尽可能简单

时间:2014-06-05 00:15:20

标签: c# json

我不是一个C#程序员,所以我对此很新,我想解析下面的示例JSON,我一直在使用代码:

    WebClient client = new WebClient();
    string getString = client.DownloadString(url);

    dynamic j = JsonConvert.DeserializeObject(getString);
    var k = j.rgDescriptions;

    dynamic m = JsonConvert.DeserializeObject(k);
    foreach (var c in m.descriptions)
          {
                Console.WriteLine(c);
          }

我在反序列化k时遇到错误,我不确定我是否在正确的路径上。如何获得“classid”而不获取其父级的值,因为它是动态的而不是命名的,它是唯一ID。

{
    "success": true,
    "rgDescriptions": {
        "671219543": {
            "id": "671219543",
            "classid": "253033065",
            "instanceid": "93973071",
            "amount": "1",
            "pos": 274
        },
        "707030894": {
            "id": "707030894",
            "classid": "166354998",
            "instanceid": "0",
            "amount": "1",
            "pos": 277
        },

更新

我使用了这段代码:

 WebClient client = new WebClient();
            string getString = client.DownloadString(url);


            var jo = JObject.Parse(getString);
            var data = (JObject)jo["rgDescriptions"];
            foreach (var item in data)
            {
                Console.WriteLine("{0}: {1}", item.Key, item.Value);
            }

我现在可以得到我想要的东西,但我需要解析每个值。还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用JSON.NET和JSONPath查询传入的JSON,示例herehere

下面的代码会为classid

中的每个对象提取rgDescriptions
//...
WebClient client = new WebClient();
string getString = client.DownloadString(url);

var obj = JObject.Parse(getString);
var classIds = obj.SelectTokens("$.rgDescriptions.*.classid").Select(x => x.Value<string>()).ToList();  //[253033065,166354998]

//Class ID Where...
var idToSearch = "671219543";
var classId = obj.SelectToken("$.rgDescriptions['" + idToSearch + "']..classid").Value<string>();
//...