【问题标题】:Parse JSON in .NET runtime在 .NET 运行时解析 JSON
【发布时间】:2010-02-03 10:13:50
【问题描述】:

我想从 WebServer 获得一些响应。

返回的数据如下所示:

[[3014887,"string1 string","http://num60.webservice.com/u3014887/b_c9c0625b.jpg",0],
[3061529,"string2 string","http://num879.webservice.com/u3061529/b_320d6d36.jpg",0],
[7317649,"string3 string","http://num1233.webservice.com/u7317649/b_a60b3dc2.jpg",0],
[12851194,"string4 string","http://num843.webservice.com/u12851194/b_4e273fa4.jpg",0],
[15819606,"string5 string","http://num9782.webservice.com/u15819606/b_66333a8f.jpg",0],
[15947248,"string6 string","http://num1500.webservice.com/u15947248/b_920c8b64.jpg",0]]

我认为是JSON 格式,但我无法在我的.Net WinForm 应用程序中解析它。 您能否提供一些建议或示例如何做到这一点。

我在 Google 上搜索了 JSON.NET 库、DataContractJsonSerializer 类,但我不明白如何将它们与响应的数据类型结合在一起......

【问题讨论】:

    标签: c# .net json


    【解决方案1】:

    如果你想解析 JSON,那么JSON.net 库就是你要找的地方。

    你可以这样使用它:

    var json = @"[[3014887,""string1 string"",""http://num60.webservice.com/u3014887/b_c9c0625b.jpg"",0], 
                          [3061529,""string2 string"",""http://num879.webservice.com/u3061529/b_320d6d36.jpg"",0],
                          [7317649,""string3 string"",""http://num1233.webservice.com/u7317649/b_a60b3dc2.jpg"",0],
                          [12851194,""string4 string"",""http://num843.webservice.com/u12851194/b_4e273fa4.jpg"",0],
                          [15819606,""string5 string"",""http://num9782.webservice.com/u15819606/b_66333a8f.jpg"",0], 
                          [15947248,""string6 string"",""http://num1500.webservice.com/u15947248/b_920c8b64.jpg"",0]]";
    var array = JArray.Parse(json);
    
    foreach (var token in array)
    {
        Console.WriteLine(token[0]);
    }
    

    这样我就可以读取你的数组的内容了。

    【讨论】:

    • 我有一个方括号。在我的示例中,还有一个值数组,而不是 KeyValue 对。在我的示例中使用 JSON.NET 是有问题的,是吗?
    • 字符串 json = GetJson(); JArray a = JArray.Parse(json);
    • 将后续步骤附加到我的答案中。
    【解决方案2】:

    WCF 命名空间中有 JSON(De) 序列化 (Windows Communication Support for AJAX Integration and JSON ) 还有非常流行的(更强大的)JSON(反)序列化库JSON.Net

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多