How to get data from JSON and convert into the object? [duplicate] - c#

This question already has answers here:
Deserializing JSON data to C# using JSON.NET
(7 answers)
Closed 5 years ago.
I'm trying to receive data from request response which is JSON like this:
{
"cnt":1,
"list":[{
"coord":{
"lon":18.55,
"lat":50.11
},
"sys":{
"type":1,
"id":5356,
"message":0.0095,
"country":"PL",
"sunrise":1496630290,
"sunset":1496688673
},
"weather":[{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01d"
}],
"main":{
"temp":293.71,
"pressure":1014,
"humidity":42,
"temp_min":293.15,
"temp_max":294.15
},
"visibility":10000,
"wind":{
"speed":4.1,
"deg":60
},
"clouds":{
"all":0
},
"dt":1496686603,
"id":7531758,
"name":"Rybnik"
}]
}
I'm trying to use JSON.NET to deserialize JSON and receive data. But I don't know exactly how to do it properly.
I tried to achieve this by using my class method:
public Rootobject DeserializeJSON()
{
private JObject responseObject;
private JToken responseToken;
private JArray responseArray;
responseObject = JObject.Parse(json);
Rootobject Weather = new Rootobject();
responseArray = (JArray)responseObject.SelectToken("list");
responseToken = (JToken)responseArray.SelectToken("main");
Weather = responseToken.ToObject<Rootobject>();
return Weather;
}
But It doesn't seems to work. In this case, I tried to receive data from "main" property in JSON and convert in to my class object:
class Main
{
public float temp { get; set; }
public float pressure { get; set; }
public float humidity { get; set; }
public float temp_min { get; set; }
public float temp_max { get; set; }
}
Could you explain me, how it should works and where's my fault, please?

Initially, you need to declare the following classes:
public class Coord
{
[JsonProperty("lon")]
public double Lon { get; set; }
[JsonProperty("lat")]
public double Lat { get; set; }
}
public class Sys
{
[JsonProperty("type")]
public int Type { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("message")]
public double Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public int Sunrise { get; set; }
[JsonProperty("sunset")]
public int Sunset { get; set; }
}
public class Weather
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public class Main
{
[JsonProperty("temp")]
public double Temp { get; set; }
[JsonProperty("pressure")]
public int Pressure { get; set; }
[JsonProperty("humidity")]
public int Humidity { get; set; }
[JsonProperty("temp_min")]
public double TempMin { get; set; }
[JsonProperty("temp_max")]
public double TempMax { get; set; }
}
public class Wind
{
[JsonProperty("speed")]
public double Speed { get; set; }
[JsonProperty("deg")]
public int Deg { get; set; }
}
public class Clouds
{
[JsonProperty("all")]
public int All { get; set; }
}
public class List
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("sys")]
public Sys Sys { get; set; }
[JsonProperty("weather")]
public IList<Weather> Weather { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public int Visibility { get; set; }
[JsonProperty("wind")]
public Wind Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public int Dt { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class Example
{
[JsonProperty("cnt")]
public int Cnt { get; set; }
[JsonProperty("list")]
public IList<List> List { get; set; }
}
Then you can deserialize your json as below:
var example = JsonConvert.DeserializeObject<Example>(jsonString)
where jsonString is your JSON.
PS. I derived the above classes using jsonutils and your json string.

Related

Using Json.net to deserialize Json with some changing object names

I'm new here so thanks for the great content; invaluable stuff.
I'm deserializing some Json from TDAmeritrade into a C# desktop app using the "Option Chain" api.
Depending on the input to the api, I can get a response with multiple expiration dates, multiple strike prices, and multiple option objects.
Here's a link to a typical response: API ResponseTDAmeritrade Json Example
A snippet of the problem code:
"numberOfContracts": 8,
"putExpDateMap": {
**"2020-08-21:50": {
"15.0":** [
{
"putCall": "PUT",
"symbol": "FMCI_082120P15",
"description": "FMCI Aug 21 2020 15 Put",
"exchangeName": "OPR",
The problem is that the dates and strike prices change in each response. I've learned that I can deserialize into a "Dictionary<string, List<Type> listName" so I did that in the OptionChain and ExpDate classes but still can't get it working.
Here is the current error: error trace
Here are my classes, created from json2csharp.com but with the date and strike price classes modified:
class OptionChain
{
public string symbol { get; set; }
public string status { get; set; }
public Underlying underlying { get; set; }
public string strategy { get; set; }
public double interval { get; set; }
public bool isDelayed { get; set; }
public bool isIndex { get; set; }
public double interestRate { get; set; }
public double underlyingPrice { get; set; }
public double volatility { get; set; }
public double daysToExpiration { get; set; }
public int numberOfContracts { get; set; }
public Dictionary<string, List<expDate>> putExpDateMap { get; set; }
public Dictionary<string, List<expDate>> callExpDateMap { get; set; }
public class expDate
{
public Dictionary<string, List<StrikePrice>> strikePrices { get; set; }
}
public class StrikePrice
{
public Option[] options { get; set; }
}
public class Option
{
public string putCall { get; set; }
public string symbol { get; set; }
public string description { get; set; }
public string exchangeName { get; set; }
public double bid { get; set; }
public double ask { get; set; }
public double last { get; set; }
public double mark { get; set; }
public int bidSize { get; set; }
public int askSize { get; set; }
public string bidAskSize { get; set; }
public int lastSize { get; set; }
public double highPrice { get; set; }
public double lowPrice { get; set; }
public double openPrice { get; set; }
public double closePrice { get; set; }
public int totalVolume { get; set; }
public object tradeDate { get; set; }
public long tradeTimeInLong { get; set; }
public long quoteTimeInLong { get; set; }
public double netChange { get; set; }
public double volatility { get; set; }
public double delta { get; set; }
public double gamma { get; set; }
public double theta { get; set; }
public double vega { get; set; }
public double rho { get; set; }
public int openInterest { get; set; }
public double timeValue { get; set; }
public double theoreticalOptionValue { get; set; }
public double theoreticalVolatility { get; set; }
public OptionDeliverablesList optionDeliverablesList { get; set; }
public double strikePrice { get; set; }
public long expirationDate { get; set; }
public int daysToExpiration { get; set; }
public string expirationType { get; set; }
public long lastTradingDay { get; set; }
public double multiplier { get; set; }
public string settlementType { get; set; }
public string deliverableNote { get; set; }
public bool isIndexOption { get; set; }
public double percentChange { get; set; }
public double markChange { get; set; }
public double markPercentChange { get; set; }
public bool inTheMoney { get; set; }
public bool mini { get; set; }
public bool nonStandard { get; set; }
public class OptionDeliverablesList
{
public string symbol { get; set; }
public string assetType { get; set; }
public double deliverableUnits { get; set; }
public string currencyType { get; set; }
}
Am I doing something wrong in the Dictionaries? The way I understand it from my many hours of reading, the expiration dates and strike prices need to be read anonymously.
Thanks a bunch!
If I get your problem right - you have probelms deserializing json structure where keys are dynamic values but not static property names, correct? If so- you have modeled incorrect POCO (there are two nested dictionaries).
POCOs below give correct deserialization results (rest of properties skipped)
class OptionChain
{
public string Symbol { get; set; }
public string Status { get; set; }
public Dictionary<string, Dictionary<string, ExpDate[]>> PutExpDateMap { get; set; }
public Dictionary<string, Dictionary<string, ExpDate[]>> CallExpDateMap { get; set; }
//other properties ignored because dont matter
}
class ExpDate
{
public string ExchangeName { get; set; }
public decimal Bid { get; set; }
public decimal Ask { get; set; }
//other properties ignored because dont matter
}
Tested POCOs with json sample provided in your post:
static void Main(string[] args)
{
var t = File.ReadAllText("test.json");
var r = JsonConvert.DeserializeObject<OptionChain>(t);
Console.WriteLine($"Total elements in {nameof(r.PutExpDateMap)} : {r.PutExpDateMap.Count()}");
Console.WriteLine($"Keys in {nameof(r.PutExpDateMap)} : {string.Join(",", r.PutExpDateMap.Keys)}");
Console.WriteLine($"Total elements in {nameof(r.CallExpDateMap)} : {r.CallExpDateMap.Count()}");
Console.WriteLine($"Keys in {nameof(r.CallExpDateMap)} : {string.Join(",", r.CallExpDateMap.Keys)}");
}
Application output is:

Deserializing JSON data to C#

Could U help me Deserializing JSON to C#? I just eat my teeth on it.. =.=.
I find many methods how to do not solve this xD,
I dont want share that with U.
I wish to wait for your suggestions.
Usefull links:
http://jsonviewer.stack.hu/
http://json2csharp.com/
JSON looks..
[
{
"faceId":"626f5974-1d63-40d4-98f1-7e6a7df13dba",
"faceRectangle":{
"top":108,
"left":699,
"width":208,
"height":208
},
"faceAttributes":{
"smile":0.973,
"gender":"male",
"age":25.7,
"emotion":{
"anger":0.0,
"contempt":0.026,
"disgust":0.0,
"fear":0.0,
"happiness":0.973,
"neutral":0.001,
"sadness":0.0,
"surprise":0.0
}
}
},
{
"faceId":"bc051f1d-9a64-4e86-bf95-2af1de21d316",
"faceRectangle":{
"top":104,
"left":634,
"width":114,
"height":114
},
"faceAttributes":{
"smile":0.074,
"gender":"male",
"age":17.4,
"emotion":{
"anger":0.003,
"contempt":0.003,
"disgust":0.001,
"fear":0.002,
"happiness":0.074,
"neutral":0.828,
"sadness":0.079,
"surprise":0.01
}
}
}
]
First of all you need classes to which you want to deserialize, so you can create manually or the fastest and easiest way - you can copy json string that you have, then in visual studio
Edit -> Paste Special -> Paste JSON as Classes
Now you have structure for deserializing.Then you can for example use Newtonsoft.Json (which you can download from NuGet). There is JsonConvert.DeserializeObject<T>() generic method, that will do all deserialization work for you.
Also, if you want use your own property names in the class structure, you can use [JsonProperty("Name")] attribute, which will change the names of properties when they are serialized to JSON and vice versa.
Your JSON document represents an array so you must deserialize it to a collection
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string jsonString = "[ {\"faceId\": \"626f5974-1d63-40d4-98f1-7e6a7df13dba\",\"faceRectangle\": { \"top\": 108, \"left\": 699, \"width\": 208, \"height\": 208 },\"faceAttributes\": { \"smile\": 0.973, \"gender\": \"male\", \"age\": 25.7, \"emotion\": { \"anger\": 0.0, \"contempt\": 0.026, \"disgust\": 0.0, \"fear\": 0.0, \"happiness\": 0.973, \"neutral\": 0.001, \"sadness\": 0.0, \"surprise\": 0.0 } }},{\"faceId\": \"bc051f1d-9a64-4e86-bf95-2af1de21d316\",\"faceRectangle\": { \"top\": 104, \"left\": 634, \"width\": 114, \"height\": 114 },\"faceAttributes\": { \"smile\": 0.074, \"gender\": \"male\", \"age\": 17.4, \"emotion\": { \"anger\": 0.003, \"contempt\": 0.003, \"disgust\": 0.001, \"fear\": 0.002, \"happiness\": 0.074, \"neutral\": 0.828, \"sadness\": 0.079, \"surprise\": 0.01 } }}]";
var result = JsonConvert.DeserializeObject<IList<RootObject>>(jsonString);
foreach ( var item in result )
Console.WriteLine( item.faceId );
}
}
// Generated by http://json2csharp.com
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class RootObject
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
.net fiddle
If you want c# object from that JSON, this is how it is done:
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class RootObject
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Instead of giving you a C# class that maps to the JSON which you'll just copy blindly, I'll recommend that you generate such a class yourself.
Make sure you're running Visual Studio 2013 SP2 or higher.
Get a JSON document for your data. If it has optional fields, make sure the one you have is as full as possible.
In a new CS file in VS, choose Edit -> Paste Special -> Paste JSON as Classes.
This will create a C# class that corresponds to the JSON data. Now, you can use JSON.NET's JsonConvert.DeserializeObject() to create it
By using NewtonsoftJson library to parse data easily
Example
dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(Jsondata); //to parse data
foreach (var product in x) {
Messagebox.show(product.data.ToString());
}
You can convert Json to c# Class
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class Example
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
Example Example_class =
Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(json.ToString());
Please see this useful link Json to C# Class https://jsonutils.com/
Do you mean something like this? To deserialize to an object?
using System.Web.Script.Serialization;
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class RootObject
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
return JsonConvert.DeserializeObject<RootObject>(jsonString);
I hope this will work
string Jsondata = "Your Json data";
public class Mainclass
{
public guid faceId;
IEnumerable<faceRectangle>
IEnumerable<faceAttributes>
}
public class faceRectangle
{
}
public class faceAttributes
{
}
Mainclass backdata = JsonConvert.DeserializeObject<Mainclass>(Jsondata , new DataConverter())

json feed as a datasource in SSIS

I am trying to deserialize a json feed from openweathermap.org api. After a lot of tries all, using script transformation task, I get is errors and even different ones. Based on the below classes generated by JSON, how I should write the for each statements (as class Weather and Main are part of class RootObject)?
I can get even XML data from api, instead of JSON. Would it be easier to implement the process?
I am not asking for the answer, just a push to start.
JSON:
{
"coord":{
"lon":-122.08,
"lat":37.39
},
"weather":[
{
"id":741,
"main":"Fog",
"description":"fog",
"icon":"50n"
}
],
"base":"stations",
"main":{
"temp":286.14,
"pressure":1022,
"humidity":82,
"temp_min":285.15,
"temp_max":287.15
},
"visibility":16093,
"wind":{
"speed":1.11,
"deg":13.5055
},
"clouds":{
"all":1
},
"dt":1479110160,
"sys":{
"type":1,
"id":397,
"message":0.1452,
"country":"US",
"sunrise":1479134859,
"sunset":1479171466
},
"id":5375480,
"name":"Mountain View",
"cod":200
}
Class:
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string #base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}

How to parse this http response in C#

How would I parse this response using C#?
[
{
"date":"2016-10-01",
"stats":[
{
"type":"subuser",
"name":"coolguy#yahoo.com",
"metrics":{
"blocks":23,
"bounce_drops":164,
"bounces":19,
"clicks":0,
"deferred":412,
"delivered":3435,
"invalid_emails":27,
"opens":0,
"processed":3481,
"requests":3675,
"spam_report_drops":3,
"spam_reports":0,
"unique_clicks":0,
"unique_opens":0,
"unsubscribe_drops":0,
"unsubscribes":0
}
}
]
},
{
"date":"2016-10-02",
"stats":[
{
"type":"subuser",
"name":"coolguy#yahoo.com",
"metrics":{
"blocks":0,
"bounce_drops":0,
"bounces":0,
"clicks":0,
"deferred":95,
"delivered":0,
"invalid_emails":0,
"opens":0,
"processed":0,
"requests":0,
"spam_report_drops":0,
"spam_reports":0,
"unique_clicks":0,
"unique_opens":0,
"unsubscribe_drops":0,
"unsubscribes":0
}
}
]
}
]
Using JsonConvert deserialize it to dynamic as below or create a matching class structure and deserialize it to that.
using Newtonsoft.Json;
.....
string json = File.ReadAllText("data.txt");
var deserializedData = JsonConvert.DeserializeObject<dynamic>(json);
Using json2csharp your classes should look like:
public class Metrics
{
public int blocks { get; set; }
public int bounce_drops { get; set; }
public int bounces { get; set; }
public int clicks { get; set; }
public int deferred { get; set; }
public int delivered { get; set; }
public int invalid_emails { get; set; }
public int opens { get; set; }
public int processed { get; set; }
public int requests { get; set; }
public int spam_report_drops { get; set; }
public int spam_reports { get; set; }
public int unique_clicks { get; set; }
public int unique_opens { get; set; }
public int unsubscribe_drops { get; set; }
public int unsubscribes { get; set; }
}
public class Stat
{
public string type { get; set; }
public string name { get; set; }
public Metrics metrics { get; set; }
}
public class RootObject
{
public string date { get; set; }
public List<Stat> stats { get; set; }
}
These generated classes can be improved - for example not storing the date in a string but a DateTime
string json = File.ReadAllText("data.txt");
RootObject deserializedData = JsonConvert.DeserializeObject<RootObject>(json);

get data from json c#

I have a problem I want to get data from Json, and the data
successfully gets from the json to the variable json but when I want to send the data to WeatherData it send me a zero value.
I have one class that cald "WeatherData" and I want to send to data from the json (that existing a class "jsonParse") to this class.
jsonParse
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Script.Serialization;
using System.IO;
namespace weather
{
public class jsonParse : Ijson
{
private string urlAdd;
public jsonParse(string _url)
{
if (_url == null)
{
//throw exption
}
else
urlAdd = _url;
}
public WeatherData parse()
{
//string json = new WebClient().DownloadString(urlAdd);
//var obj = JsonConvert.DeserializeObject<WeatherData>(json);
//Console.WriteLine(obj.temp);
// WeatherData m = JsonConvert.DeserializeObject<WeatherData>(json);
WebClient n = new WebClient();
var json = n.DownloadString(urlAdd);
string valueOriginal = Convert.ToString(json);
WeatherData m = JsonConvert.DeserializeObject<WeatherData>(json);
Console.WriteLine(m);
return m;
}
}
}
WeatherData
namespace weather
{
public class WeatherData
{
public WeatherData(double _temp, double _minTemp, double _maxTemp )
{
temp = _temp;
minTemp = _minTemp;
maxTemp = _maxTemp;
}
public double temp { get; set; }
public double minTemp { get; set; }
public double maxTemp { get; set; }
public override string ToString()
{
return "the weather:" + temp + "minTemp is:" + minTemp + "maxTemp:" + maxTemp;
}
}
}
json
{"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200}
If you only care about the weather part of the json, try this -
var o = (JArray)JObject.Parse(jsonString)["weather"];
foreach(JToken item in o)
{
Console.WriteLine(((JValue)item["id"]).Value);
Console.WriteLine(((JValue)item["main"]).Value);
Console.WriteLine(((JValue)item["description"]).Value);
Console.WriteLine(((JValue)item["icon"]).Value);
}
First object in json is coord, don't see that in your model.
You should change your JsonModel to deserialize. From c# class generator:
public class Coord
{
public int lon { get; set; }
public int lat { get; set; }
}
public class Sys
{
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int humidity { get; set; }
public int pressure { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Rain
{
public int __invalid_name__3h { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
Where RootObject is your JsonConvert.DeserializeObject(json);
So you can change class names as you like.
Simply you cannot Deserialize a json object to a non-matching class object. So make sure you have a model object that have atleast all the properties that JSON object have.
In this case you would need following classes that are generated from your JSON object:
public class Coord
{
public int lon { get; set; }
public int lat { get; set; }
}
public class Sys
{
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int humidity { get; set; }
public int pressure { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Rain
{
public int __invalid_name__3h { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class ParentModel
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
ParentModel m = JsonConvert.DeserializeObject<ParentModel>(json);
Hope this helps.

Categories

Resources