2015-07-03 5 views
-1

Мне нужно разобрать эту строку JSON для объекта типа WeatherJson. Однако я не знаю, как разбирать массивы внутри строки, такие как «погода»: [{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}]. Как выглядит класс класса?Как проанализировать этот результат JSON как объект?

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 
} 

EDIT

Мне нужно получить следующие значения из кода:

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 
+0

Ну, что делает ваш 'WeatherJson' тип выглядеть? У вас уже есть код, чтобы попытаться разобрать? Если да, что будет, когда вы попробуете? –

+0

Посмотрите на это [Как разобрать JSON в C#] [1] [1]: http://stackoverflow.com/a/6620173/1129313 – Garry

+0

Я знаю, как разобрать нормальный JSON такие как: message ": 0.0145. Моя проблема заключается в извлечении массивов и их хранении в объекте @JonSkeet – Dinuka

ответ

4

Вы должны просто сделать массивы в матче с 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; } 
} 
+0

Спасибо, это объясняло все, что мне нужно было знать! – Dinuka

1

Try двойной итерации,

for (key in parent) { 
    for(key1 in parent[key]){ 
    // 
    } 
} 
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"); 
     } 
    } 
} 
1

JObject определяет метод Разбор для этого:

JObject json = JObject.Parse(JsonString); 

Вы можете обратиться к Json.NET documentation.

Если у вас есть коллекция объектов, то вы можете использовать JArray

JArray jarr = JArray.Parse(JsonString); 

Для документации вы можете увидеть here.

Чтобы преобразовать JArry в список Просто введите ниже метод. Он вернет вам то, что вам нужно.

Jarray.ToObject<List<SelectableEnumItem>>() 
1

Попробуйте эту надежду это поможет вам ....

 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. 
0

Вы можете использовать JavaScriptSerializer класс для разбора JSON в объект.

См этот StackOverflow нить

Смежные вопросы