【问题标题】:How do I parse this JSON Result as an object?如何将此 JSON 结果解析为对象?
【发布时间】:2015-07-03 06:10:20
【问题描述】:

我需要将此 JSON 字符串解析为“WeatherJson”类型的对象。但是我不知道如何解析字符串中的数组,例如 '"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}]。实体类会是什么样子?

JSON 字符串:

{
  "coord": {"lon":79.85,"lat":6.93},
  "sys": {
    "type": 1, 
    "id": 7864, 
    "message": 0.0145,
    "country": "LK",
    "sunrise": 1435883361,
    "sunset": 1435928421
  },
  "weather": [
     {"id":802, "main":"Clouds", "description":"scattered clouds", "icon":"03d"}
  ],
  "base": "stations",
  "main": {
    "temp": 302.15,
    "pressure": 1013,
    "humidity": 79,
    "temp_min": 302.15,
    "temp_max": 302.15
  },
  "visibility":10000,
  "wind": { "speed": 4.1, "deg": 220 },
  "clouds": { "all": 40 },
  "dt": 1435893000,
  "id":1248991,
  "name":"Colombo",
  "cod":200
}

编辑

我需要从代码中检索以下值:

WeatherJson w = new WeatherJson();
Console.WriteLine(w.weather.description);
//that above line was retrieved and stored from the JSONArray named 'weather' in the main json response

【问题讨论】:

  • 那么您的WeatherJson 类型是什么样的?您是否已经有一些代码可以尝试解析?如果是这样,当您尝试时会发生什么?
  • 看看这个[如何在C#中解析json][1][1]:stackoverflow.com/a/6620173/1129313
  • 我确实知道如何解析普通的 json 数据,例如:message":0.0145。我的问题是检索数组并将其存储在 @JonSkeet 对象中
  • 又一次,你有什么尝试?只需在您的数据类型中将它们设为数组或列表即可。 (顺便说一句,我已重新格式化 JSON 以使其更易于阅读。)
  • 好吧,still 还没有显示 WeatherJson 类型,因为 weather 是一个数组,它应该是你类型中的一个数组 - 所以你会需要w.Weather[0].Description

标签: c# .net json json.net


【解决方案1】:

您应该只使 JSON 中的数组与 POCO 中的列表或数组类型匹配。这是一个使用您提供的 JSON 的简短但完整的示例:

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Test
{ 
    static void Main(string[] args) 
    {
        var json = File.ReadAllText("weather.json");
        var root = JsonConvert.DeserializeObject<Root>(json);
        Console.WriteLine(root.Weather[0].Description);
    }
}

public class Root
{
    // Just a few of the properties
    public Coord Coord { get; set; }
    public List<Weather> Weather { get; set; }
    public int Visibility { get; set; }
    public string Name { get; set; }
}

public class Weather
{
    public int Id { get; set; }
    public string Description { get; set; }
}

public class Coord
{
    public double Lon { get; set; }
    public double Lat { get; set; }
}

【讨论】:

  • 谢谢!这解释了我需要知道的一切!
【解决方案2】:

试试这样:

void Main()
{
    var json = System.IO.File.ReadAllText(@"d:\test.json");

    var objects = JArray.Parse(json); // parse as array  
    foreach(JObject root in objects)
    {
        foreach(KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            var description = (String)app.Value["Description"];
            var value = (String)app.Value["Value"];

            Console.WriteLine(appName);
            Console.WriteLine(description);
            Console.WriteLine(value);
            Console.WriteLine("\n");
        }
    }
}

【讨论】:

    【解决方案3】:

    试试这个希望对你有帮助....

          var dataObj=JSON.parse {"coord":{"lon":79.85,"lat":6.93},"sys":
          {"type":1,"id":7864,"message":0.0145,"country":"LK",
     "sunrise":1435883361,
    "sun        set":1435928421},"weather":     [{"id":802,"main":"Clouds",
        "description":"scattered    clouds","icon":"03d"}],
      "base":"stations","main":{"temp":302.15,"pressure":1013,
    "humidity":79,"temp_min":302.15,
     "temp_max":302.15},"visibility":10000,"wind":{"speed":4.1,"deg":220},
     "clouds":{"all":40},"dt":1435893000,"id":1248991,
      "name":"Colombo","cod":200}
    
    to read this .
    i m reading one single string so u can able to know.
    
    var windData=dataObj.wind.speed;
     it will read value 4.1 from your string like this..
    
    If u want to read array of string then..
    var weatherObj=dataObj.weather[0].description;
    
    so it will read  description value from array.like this u can read.
    

    【讨论】:

      【解决方案4】:

      尝试双重迭代,

      for (key in parent) {
           for(key1 in parent[key]){
           //
           }
      } 
      

      【讨论】:

        【解决方案5】:

        JObject 为此定义了 Parse 方法:

        JObject json = JObject.Parse(JsonString);
        

        您可能想参考 Json.NET documentation

        如果你有对象的集合,那么你可以使用 JArray

        JArray jarr = JArray.Parse(JsonString);
        

        有关文档,您可以查看here

        将 JArry 转换为 List 只需把下面的方法。它会返回你需要的东西。

        Jarray.ToObject<List<SelectableEnumItem>>()
        

        【讨论】:

          【解决方案6】:

          您可以使用 JavaScriptSerializer 类将 JSON 解析为 Object。

          参考这个StackOverflow 线程

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-05-22
            • 1970-01-01
            • 1970-01-01
            • 2017-03-18
            相关资源
            最近更新 更多