Im still newbie and learning some API calls. Just dont know why code dont convert from string to Newtonsoft.Json.Linq.JObject.
WebRequest request = WebRequest.Create("https://api.pandascore.co/lol/champions?filter[name]=Brand&token==mytoken");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseFromServer = reader.ReadToEnd();
JObject parsedString = JObject.Parse(responseFromServer);
Champions champion = parsedString.ToObject<Champions>();
return View(champion);
and in debug mode responseFromServer is a string
and result is looking ok, but this dont convert to object. parsedString = null.
Newtonsoft.Json.JsonReaderException: „Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path
Champions class look like:
public class Champions
{
public List<string> videogame_versions { get; set; }
public double spellblockperlevel { get; set; }
public double spellblock { get; set; }
public string name { get; set; }
public double mpregenperlevel { get; set; }
public double mpregen { get; set; }
public double mpperlevel { get; set; }
public double mp { get; set; }
public double movespeed { get; set; }
public string image_url { get; set; }
public int id { get; set; }
public double hpregenperlevel { get; set; }
public double hpregen { get; set; }
public double hpperlevel { get; set; }
public double hp { get; set; }
public double critperlevel { get; set; }
public double crit { get; set; }
public string big_image_url { get; set; }
public double attackspeedperlevel { get; set; }
public object attackspeedoffset { get; set; }
public double attackrange { get; set; }
public double attackdamageperlevel { get; set; }
public double attackdamage { get; set; }
public double armorperlevel { get; set; }
public double armor { get; set; }
}
}
my JSON string looks like :
[
{
"videogame_versions": [
"9.10.1",
"9.9.1",
"9.8.1",
"9.7.2",
"9.7.1",
"9.6.1",
"9.5.1",
"9.4.1",
"9.3.1",
"9.2.1",
"9.1.1",
"8.24.1",
"8.23.1",
"8.22.1"
],
"spellblockperlevel": 0.5,
"spellblock": 30,
"name": "Brand",
"mpregenperlevel": 0.6,
"mpregen": 10.665,
"mpperlevel": 21,
"mp": 469,
"movespeed": 340,
"image_url": "https://cdn.pandascore.co/images/lol/champion/image/7aa667709a7ce82e45c459e3df2d160a.png",
"id": 2347,
"hpregenperlevel": 0.55,
"hpregen": 5.5,
"hpperlevel": 88,
"hp": 519.68,
"critperlevel": 0,
"crit": 0,
"big_image_url": "https://cdn.pandascore.co/images/lol/champion/big_image/8ba7fd90e7c250b2dcc3183205ad6d94.jpg",
"attackspeedperlevel": 1.36,
"attackspeedoffset": null,
"attackrange": 550,
"attackdamageperlevel": 3,
"attackdamage": 57.04,
"armorperlevel": 3.5,
"armor": 21.88
}
]
offers 6 kingdoms and broken wheel for help
The trick here is to deserialize into a List<Champions> as your root level JSON data is an array.
public static class Program
{
private static void Main(string[] args)
{
string data = #"
[
{
'videogame_versions': [
'9.10.1',
'9.9.1',
'9.8.1',
'9.7.2',
'9.7.1',
'9.6.1',
'9.5.1',
'9.4.1',
'9.3.1',
'9.2.1',
'9.1.1',
'8.24.1',
'8.23.1',
'8.22.1'
],
'spellblockperlevel': 0.5,
'spellblock': 30,
'name': 'Brand',
'mpregenperlevel': 0.6,
'mpregen': 10.665,
'mpperlevel': 21,
'mp': 469,
'movespeed': 340,
'image_url': 'https://cdn.pandascore.co/images/lol/champion/image/7aa667709a7ce82e45c459e3df2d160a.png',
'id': 2347,
'hpregenperlevel': 0.55,
'hpregen': 5.5,
'hpperlevel': 88,
'hp': 519.68,
'critperlevel': 0,
'crit': 0,
'big_image_url': 'https://cdn.pandascore.co/images/lol/champion/big_image/8ba7fd90e7c250b2dcc3183205ad6d94.jpg',
'attackspeedperlevel': 1.36,
'attackspeedoffset': null,
'attackrange': 550,
'attackdamageperlevel': 3,
'attackdamage': 57.04,
'armorperlevel': 3.5,
'armor': 21.88
}
]
";
List<Champions> champions = JsonConvert.DeserializeObject<List<Champions>>(data);
}
public class Champions
{
public List<string> videogame_versions { get; set; }
public double spellblockperlevel { get; set; }
public double spellblock { get; set; }
public string name { get; set; }
public double mpregenperlevel { get; set; }
public double mpregen { get; set; }
public double mpperlevel { get; set; }
public double mp { get; set; }
public double movespeed { get; set; }
public string image_url { get; set; }
public int id { get; set; }
public double hpregenperlevel { get; set; }
public double hpregen { get; set; }
public double hpperlevel { get; set; }
public double hp { get; set; }
public double critperlevel { get; set; }
public double crit { get; set; }
public string big_image_url { get; set; }
public double attackspeedperlevel { get; set; }
public object attackspeedoffset { get; set; }
public double attackrange { get; set; }
public double attackdamageperlevel { get; set; }
public double attackdamage { get; set; }
public double armorperlevel { get; set; }
public double armor { get; set; }
}
}
JObject represents a JSON Object which is known as { /*key value pairs*/ } and what it actually should be is JArray
If you don't want to specify as a JSON Object or a JSON Array, you can use JToken instead.
If your json in array then you must need to convert List object
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var json = #"[
{
'videogame_versions': [
'9.10.1',
'9.9.1',
'9.8.1',
'9.7.2',
'9.7.1',
'9.6.1',
'9.5.1',
'9.4.1',
'9.3.1',
'9.2.1',
'9.1.1',
'8.24.1',
'8.23.1',
'8.22.1'
],
'spellblockperlevel': 0.5,
'spellblock': 30,
'name': 'Brand',
'mpregenperlevel': 0.6,
'mpregen': 10.665,
'mpperlevel': 21,
'mp': 469,
'movespeed': 340,
'image_url': 'https://cdn.pandascore.co/images/lol/champion/image/7aa667709a7ce82e45c459e3df2d160a.png',
'id': 2347,
'hpregenperlevel': 0.55,
'hpregen': 5.5,
'hpperlevel': 88,
'hp': 519.68,
'critperlevel': 0,
'crit': 0,
'big_image_url': 'https://cdn.pandascore.co/images/lol/champion/big_image/8ba7fd90e7c250b2dcc3183205ad6d94.jpg',
'attackspeedperlevel': 1.36,
'attackspeedoffset': null,
'attackrange': 550,
'attackdamageperlevel': 3,
'attackdamage': 57.04,
'armorperlevel': 3.5,
'armor': 21.88
}
]";
List<Champions> champions = JsonConvert.DeserializeObject<List<Champions>>(json);
}
}
Related
these are my classes.
public class BasketClass
{
public int HowMany { get; set; }
public int MBasketId { get; set; }
public int MVendorId { get; set; }
public int WInvestorId { get; set; }
public int MProductId { get; set; }
}
public class VendorPay
{
public int id { get; set; }
public int MVendorId { get; set; }
public bool IsCargoIncluded { get; set; }
public decimal CargoAmount { get; set; }
public decimal TotalAmount { get; set; }
}
public class PayBasketInputClass
{
public List<BasketClass> mOrderList { get; set; }
public List<VendorPay> vendorPayList { get; set; }
}
And this is my method.
public IActionResult PayBasket(int WInvestorId, PayBasketInputClass payInput, string paymenttype)
I gotta send payInput from body. But it includes two lists and its to complicated for me. Can you help me how to do it with an example?
Cheers.
{
"mOrderList": [
{
"HowMany": 1,
"MBasketId": 2,
"MVendorId": 3,
"WInvestorId": 4,
"MProductId": 5
}
],
"vendorPayList": [
{
"id": 1,
"MVendorId": 2,
"IsCargoIncluded": true,
"CargoAmount": 3.99,
"TotalAmount": 4.99
}
]
}
Json object is above is your PayBasketInputClass object in json structure.
I am pulling in quote data from TD Ameritrade's API, and it's generating the following JSON:
{
"AAPL": {
"52WkHigh": 145.09,
"52WkLow": 53.1525,
"askId": "P",
"askPrice": 121.08,
"askSize": 1700,
"assetMainType": "EQUITY",
"assetType": "EQUITY",
"bidId": "P",
"bidPrice": 121.06,
"bidSize": 600,
"bidTick": " ",
"closePrice": 121.03,
"cusip": "037833100",
"delayed": "false",
"description": "Apple Inc. - Common Stock",
"digits": 4,
"divAmount": 0.82,
"divDate": "2021-02-05 00:00:00.000",
"divYield": 0.68,
"exchange": "q",
"exchangeName": "NASD",
"highPrice": 121.17,
"lastId": "D",
"lastPrice": 121.08,
"lastSize": 200,
"lowPrice": 119.16,
"marginable": "true",
"mark": 121.03,
"markChangeInDouble": 0.0,
"markPercentChangeInDouble": 0.0,
"nAV": 0.0,
"netChange": 0.05,
"netPercentChangeInDouble": 0.0413,
"openPrice": 120.4,
"peRatio": 32.9702,
"quoteTimeInLong": 1615597198023,
"regularMarketLastPrice": 121.03,
"regularMarketLastSize": 7,
"regularMarketNetChange": 0.0,
"regularMarketPercentChangeInDouble": 0.0,
"regularMarketTradeTimeInLong": 1615582801729,
"securityStatus": "Normal",
"shortable": "true",
"symbol": "AAPL",
"totalVolume": 88105050,
"tradeTimeInLong": 1615597198932,
"volatility": 0.0085
}
}
Class created from JSON:
public class Quote
{
public float _52WkHigh { get; set; }
public float _52WkLow { get; set; }
public string askId { get; set; }
public float askPrice { get; set; }
public int askSize { get; set; }
public string assetMainType { get; set; }
public string assetType { get; set; }
public string bidId { get; set; }
public float bidPrice { get; set; }
public int bidSize { get; set; }
public string bidTick { get; set; }
public float closePrice { get; set; }
public string cusip { get; set; }
public string delayed { get; set; }
public string description { get; set; }
public int digits { get; set; }
public float divAmount { get; set; }
public string divDate { get; set; }
public float divYield { get; set; }
public string exchange { get; set; }
public string exchangeName { get; set; }
public float highPrice { get; set; }
public string lastId { get; set; }
public float lastPrice { get; set; }
public int lastSize { get; set; }
public float lowPrice { get; set; }
public string marginable { get; set; }
public float mark { get; set; }
public float markChangeInDouble { get; set; }
public float markPercentChangeInDouble { get; set; }
public float nAV { get; set; }
public float netChange { get; set; }
public float netPercentChangeInDouble { get; set; }
public float openPrice { get; set; }
public float peRatio { get; set; }
public long quoteTimeInLong { get; set; }
public float regularMarketLastPrice { get; set; }
public int regularMarketLastSize { get; set; }
public float regularMarketNetChange { get; set; }
public float regularMarketPercentChangeInDouble { get; set; }
public long regularMarketTradeTimeInLong { get; set; }
public string securityStatus { get; set; }
public string shortable { get; set; }
public string symbol { get; set; }
public int totalVolume { get; set; }
public long tradeTimeInLong { get; set; }
public float volatility { get; set; }
}
I am calling a Python Script to get the JSON data, which then redirects to my C# app.
However, when I deserialize it, no data is populating:
public void GetQuotes(string symbol)
{
var errors = "";
var results = "";
this.psi.Arguments = $"\"{this.script}\" -q {symbol}";
Quote quote;
using (var process = Process.Start(psi))
{
errors = process.StandardError.ReadToEnd();
results = process.StandardOutput.ReadToEnd();
Debug.Print(results);
quote = JsonConvert.DeserializeObject<Quote>(results);
}
MessageBox.Show(quote.symbol);
}
I have been able to deserialize Json with relatively consistent success, but I can't figure out why I'm loading in blank objects from this JSON.
You need to create a root object that contains your Quote object.
public class RootObject
{
public Quote AAPL { get;set;}
}
and deserialize to this,
var rootObject = JsonConvert.DeserializeObject<RootObject>(results);
Quote quote = rootObject.AAPL;
When you deserialize to Quote, you are getting nulls because there is no property in the original json that matches with any of the Quote properties. Since your JSON contains 1 property (AAPL) and its value is of type Quote, you have to deserialize to RootObject.
Based on your point on variable key, you should deserialize to Dictionary<string, Quote>.
var obj = JsonConvert.DeserializeObject<Dictionary<string, Quote>>(results);
Quote quote = obj.FirstOrDefault().Value;
You can also list all keys and use foreach loop but if you know there will always be only one key, FirstOrDefault() will work as well.
Thanks to Jawad for the quick hint. Because 'AAPL' is an ever-changing key, I had to deserialize the JSON into a Dictionary<string, Quote> to get the data populating:
public void GetQuotes(string symbol)
{
var errors = "";
var results = "";
this.psi.Arguments = $"\"{this.script}\" -q {symbol}";
Dictionary<string, Quote> quotes;
using (var process = Process.Start(psi))
{
errors = process.StandardError.ReadToEnd();
results = process.StandardOutput.ReadToEnd();
Debug.Print(results);
quotes = JsonConvert.DeserializeObject<Dictionary<string, Quote>>(results);
}
}
I have a json data as below -
{
"request": {
"type": "",
"query": "",
"language": "en",
"unit": "m"
},
"location": {
"name": "",
"country": "",
"region": "",
"lat": "",
"lon": "",
"timezone_id": "Asia/Kolkata",
"localtime": "2020-05-29 23:30",
"localtime_epoch": 1590795000,
"utc_offset": "5.50"
},
"current": {
"observation_time": "06:00 PM",
"temperature": 40,
"weather_code": 116,
"weather_icons": [
""
],
"weather_descriptions": [
"Partly cloudy"
],
"wind_speed": 9,
"wind_degree": 230,
"wind_dir": "SW",
"pressure": 1006,
"precip": 0,
"humidity": 26,
"cloudcover": 25,
"feelslike": 42,
"uv_index": 1,
"visibility": 6,
"is_day": "no"
},
"forecast": {
"2020-05-28": {
"date": "2020-05-28",
"date_epoch": 1590624000,
"astro": {
"sunrise": "05:41 AM",
"sunset": "06:46 PM",
"moonrise": "10:29 AM",
"moonset": "11:48 PM",
"moon_phase": "First Quarter",
"moon_illumination": 39
},
"mintemp": 32,
"maxtemp": 44,
"avgtemp": 38,
"totalsnow": 0,
"sunhour": 13.1,
"uv_index": 9
}
}
}
First Three nodes("request","location","current") are binding properly but for "forecast" since the first node is a date time. I have written in the following way-
var dataObjects = JsonConvert.DeserializeObject<Location_Weather.Weather>(customerJsonString);
var dataObjects23 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>> (customerJsonString);
dynamic forecast_details = dataObjects23["forecast"];
This is my Model->
public class New_Location_Weather
{
[JsonProperty("request")]
public Request Request { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
[JsonProperty("current")]
public Current Current { get; set; }
[JsonProperty("forecast")]
public Forecast Forecast { get; set; }
}
public partial class Current
{
[JsonProperty("observation_time")]
public string ObservationTime { get; set; }
[JsonProperty("temperature")]
public long Temperature { get; set; }
[JsonProperty("weather_code")]
public long WeatherCode { get; set; }
[JsonProperty("weather_icons")]
public Uri[] WeatherIcons { get; set; }
[JsonProperty("weather_descriptions")]
public string[] WeatherDescriptions { get; set; }
[JsonProperty("wind_speed")]
public long WindSpeed { get; set; }
[JsonProperty("wind_degree")]
public long WindDegree { get; set; }
[JsonProperty("wind_dir")]
public string WindDir { get; set; }
[JsonProperty("pressure")]
public long Pressure { get; set; }
[JsonProperty("precip")]
public long Precip { get; set; }
[JsonProperty("humidity")]
public long Humidity { get; set; }
[JsonProperty("cloudcover")]
public long Cloudcover { get; set; }
[JsonProperty("feelslike")]
public long Feelslike { get; set; }
[JsonProperty("uv_index")]
public long UvIndex { get; set; }
[JsonProperty("visibility")]
public long Visibility { get; set; }
[JsonProperty("is_day")]
public string IsDay { get; set; }
}
public partial class Forecast
{
[JsonProperty("2020-05-28")]
public The20200528 The20200528 { get; set; }
}
public partial class The20200528
{
[JsonProperty("date")]
public DateTimeOffset Date { get; set; }
[JsonProperty("date_epoch")]
public long DateEpoch { get; set; }
[JsonProperty("astro")]
public Astro Astro { get; set; }
[JsonProperty("mintemp")]
public long Mintemp { get; set; }
[JsonProperty("maxtemp")]
public long Maxtemp { get; set; }
[JsonProperty("avgtemp")]
public long Avgtemp { get; set; }
[JsonProperty("totalsnow")]
public long Totalsnow { get; set; }
[JsonProperty("sunhour")]
public double Sunhour { get; set; }
[JsonProperty("uv_index")]
public long UvIndex { get; set; }
}
public partial class Astro
{
[JsonProperty("sunrise")]
public string Sunrise { get; set; }
[JsonProperty("sunset")]
public string Sunset { get; set; }
[JsonProperty("moonrise")]
public string Moonrise { get; set; }
[JsonProperty("moonset")]
public string Moonset { get; set; }
[JsonProperty("moon_phase")]
public string MoonPhase { get; set; }
[JsonProperty("moon_illumination")]
public long MoonIllumination { get; set; }
}
public partial class Location
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
[JsonProperty("lon")]
public string Lon { get; set; }
[JsonProperty("timezone_id")]
public string TimezoneId { get; set; }
[JsonProperty("localtime")]
public string Localtime { get; set; }
[JsonProperty("localtime_epoch")]
public long LocaltimeEpoch { get; set; }
[JsonProperty("utc_offset")]
public string UtcOffset { get; set; }
}
public partial class Request
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("query")]
public string Query { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("unit")]
public string Unit { get; set; }
}
Now issue is I am not able to get the values. I need some guidance on how to get this values from the dynamic object which is forecast_details into my C# code.
Below is the screenshot of the values which I need to access them in my c# code
While debugging the dynamic object I found the values in my result view. But I am not sure how to access those values in my c# code.
Please do let me know on how to get these values from my C# dynamic object(forecast_details).
Look at this question, there is two answers that can help you.
How to add properties at runtime to JSON (C#)
You can parse your forecast json to JObject, and get all values from it with foreach.
This is what I figured it out. Hope it helps for others to.
JObject obj = JObject.Parse(customerJsonString);
var forecast_details = obj.SelectToken("forecast").Children().OfType<JProperty>()
.ToDictionary(p => p.Name, p => new
{
MaxTemp = (int)p.First()["maxtemp"],
MinTemp = (int)p.First()["mintemp"]
});
if(forecast_details.Count>0)
{
int max_temp = forecast_details.Values.Select(x => x.MaxTemp).FirstOrDefault();
int min_temp = forecast_details.Values.Select(x => x.MinTemp).FirstOrDefault();
}
I'm trying to extend the HelpScoutNet project so I can take advantage of reports. I'm having one hell of a time getting the JSON I get from HelpScout to deserialize into my classes. Hopefully you guys can tell me what I'm doing wrong.
JSON according to the API documents:
{
"filterTags": [
{
"id": 123,
"name": "sample-tag"
},
...
],
"user": {
"id": 4,
"hasPhoto": true,
"createdAt": "2010-09-03T15:55:48Z",
"name": "John Smith",
"totalCustomersHelped": 6580,
"photoUrl": "http://example.com/pic.jpg"
},
"current": {
"startDate": "2015-01-01T00:00:00Z",
"endDate": "2015-01-31T23:59:59Z",
"totalDays": 30,
"resolved": 1,
"conversationsCreated": 15,
"closed": 3,
"totalReplies": 58,
"resolvedOnFirstReply": 0,
"percentResolvedOnFirstReply": 0.0,
"repliesToResolve": 2.0,
"handleTime": 78.96,
"happinessScore": 66.66666666666666,
"responseTime": 2278004,
"resolutionTime": 2278004.0,
"repliesPerDay": 1.9333333333333333,
"customersHelped": 26,
"totalConversations": 19,
"conversationsPerDay": 0.6333333333333333,
"busiestDay": 5
},
"previous": {
"startDate": "2014-01-01T00:00:00Z",
"endDate": "2014-01-31T23:59:59Z",
"totalDays": 30,
"resolved": 12,
"conversationsCreated": 2,
"closed": 33,
"totalReplies": 40,
"resolvedOnFirstReply": 4,
"percentResolvedOnFirstReply": 0.3333333333333333,
"repliesToResolve": 2.1666666666666665,
"handleTime": 0.0,
"happinessScore": 23.529411764705884,
"responseTime": 2357169,
"resolutionTime": 4318101.5,
"repliesPerDay": 1.3333333333333333,
"customersHelped": 16,
"totalConversations": 42,
"conversationsPerDay": 0.4
},
"deltas": {
"totalConversations": -54.761904761904766,
"customersHelped": 62.5,
"happinessScore": 43.13725490196077,
"repliesPerDay": 45.000000000000014,
"resolvedOnFirstReply": -100.0,
"handleTime": 0.0,
"conversationsPerDay": 58.33333333333333,
"resolved": -91.66666666666666,
"repliesToResolve": -7.692307692307687,
"activeConversations": -54.761904761904766,
"totalReplies": 44.99999999999999,
"closed": -90.9090909090909,
"responseTime": -3.3584779029420475,
"resolutionTime": -47.245241919394445,
"conversationsCreated": 650.0
}
}
JSON I get back from API:
"{\"filterTags\":[{\"name\":\"general questions\",\"id\":295508},{\"name\":\"request/suggestion\",\"id\":372291},{\"name\":\"support.dd.com incorrect\",\"id\":547376},{\"name\":\"status update\",\"id\":295502},{\"name\":\"support.dd.com other\",\"id\":547378},{\"name\":\"promos/gift cards\",\"id\":295547}],\"user\":{\"createdAt\":\"2015-05-04T16:32:21Z\",\"photoUrl\":\"https://d33v4339jhl8k0.cloudfront.net/users/99999.23342.jpg\",\"hasPhoto\":true,\"name\":\"John Doe\",\"totalCustomersHelped\":261,\"id\":99999},\"current\":{\"startDate\":\"2015-08-15T12:00:00Z\",\"endDate\":\"2015-08-16T18:00:00Z\",\"totalDays\":1,\"resolved\":4,\"conversationsCreated\":0,\"closed\":11,\"totalReplies\":5,\"resolvedOnFirstReply\":3,\"percentResolvedOnFirstReply\":60.0,\"repliesToResolve\":1.25,\"handleTime\":346.6,\"happinessScore\":0.0,\"responseTime\":3467,\"resolutionTime\":4704.25,\"repliesPerDay\":5.0,\"customersHelped\":4,\"totalConversations\":12,\"conversationsPerDay\":12.0,\"busiestDay\":6}}"
My Classes:
public class User
{
[DefaultValue(0)]
public int ID { get; set; }
public bool HasPhoto { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? CreatedAt { get; set; }
public string Name { get; set; }
public int TotalCustomersHelped { get; set; }
public string PhotoURL { get; set; }
}
public class TimeRangeStats
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? StartDate { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? EndDate { get; set; }
public int TotalDays { get; set; }
public int Resolved { get; set; }
public int ConversationsCreated { get; set; }
public int Closed { get; set; }
public int TotalReplies { get; set; }
public int ResolvedOnFirstReply { get; set; }
public double PercentResolvedOnFirstReply { get; set; }
public double RepliesToResolve { get; set; }
public double HandleTime { get; set; }
public double HappinessScore { get; set; }
public double ResponseTime { get; set; }
public double ResolutionTime { get; set; }
public double RepliesPerDay { get; set; }
public int CustomersHelped { get; set; }
public int TotalConversations { get; set; }
public double ConversationsPerDay { get; set; }
public int BusiestDay { get; set; }
}
public class MultipleTimeRangeStats
{
public double TotalConversations { get; set; }
public double CustomersHelped { get; set; }
public double HappinessScore { get; set; }
public double RepliesPerDay { get; set; }
public double ResolvedOnFirstReply { get; set; }
public double HandleTime { get; set; }
public double ConversationsPerDay { get; set; }
public double Resolved { get; set; }
public double RepliesToResolve { get; set; }
public double ActiveConversations { get; set; }
public double TotalReplies { get; set; }
public double Closed { get; set; }
public double ResponseTime { get; set; }
public double ResolutionTime { get; set; }
public double ConversationsCreated { get; set; }
}
public class Tag
{
public string Name { get; set; }
[DefaultValue(0)]
public long ID { get; set; }
}
public class UserReport
{
public List<Tag> FilterTags { get; set; }
public User User { get; set; }
public TimeRangeStats Current { get; set; }
public TimeRangeStats Previous { get; set; }
public MultipleTimeRangeStats Deltas { get; set; }
}
Serializer Settings:
private JsonSerializerSettings _serializerSettings
{
get
{
var serializer = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
};
serializer.Converters.Add(new StringEnumConverter {CamelCaseText = true});
return serializer;
}
}
I hope this is not an overwhelming amount of information to ask about.
HelpScoutNet: https://github.com/Selz/HelpScoutNet
Relevant HelpScout API: http://developer.helpscout.net/help-desk-api/reports/user/user/
Edit: Got the tracer to work, get this result. Which is thoroughly confusing that it can't find those properties yet it works on other classes that as far as I can tell are built the same:
2015-08-18T00:59:30.188 Info Started deserializing HelpScoutNet.SingleItem`1[Hel
pScoutNet.Model.Report.User.UserReports.UserReport]. Path 'filterTags', line 1,
position 14.
2015-08-18T00:59:30.189 Verbose Could not find member 'filterTags' on HelpScoutN
et.SingleItem`1[HelpScoutNet.Model.Report.User.UserReports.UserReport]. Path 'fi
lterTags', line 1, position 14.
2015-08-18T00:59:30.194 Verbose Could not find member 'user' on HelpScoutNet.Sin
gleItem`1[HelpScoutNet.Model.Report.User.UserReports.UserReport]. Path 'user', l
ine 1, position 276.
2015-08-18T00:59:30.198 Verbose Could not find member 'current' on HelpScoutNet.
SingleItem`1[HelpScoutNet.Model.Report.User.UserReports.UserReport]. Path 'curre
nt', line 1, position 470.
2015-08-18T00:59:30.200 Info Finished deserializing HelpScoutNet.SingleItem`1[He
lpScoutNet.Model.Report.User.UserReports.UserReport]. Path '', line 1, position
896.
The JSON in your question corresponds to your UserReport class, not a SingleItem<UserReport> -- there's no outer {"item": ...} container object. So you need to deserialize it as such.
How can we extract or retrieve child nodes values from JSON structure in C#.
my app is using OpenWeatherMap, I need to retrieve name from city, temp from list and description from weather nodes, my JSON and Class structure are below
{
"cod": "200",
"message": 0.0284,
"city": {
"id": 2643743,
"name": "London",
"coord": {
"lon": -0.12574,
"lat": 51.50853
},
"country": "GB",
"population": 0,
"sys": {
"population": 0
}
},
"cnt": 1,
"list": [
{
"dt": 1429268400,
"temp": {
"day": 12.21,
"min": 4.86,
"max": 13.18,
"night": 4.86,
"eve": 11.76,
"morn": 12.21
},
"pressure": 1028.8,
"humidity": 66,
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"speed": 5.9,
"deg": 67,
"clouds": 80
}
]
}
C# Class
public class WeatherForeCast
{
public string City { get; set; }
public decimal Day { get; set; }
public decimal Min { get; set; }
public decimal Max { get; set; }
public decimal Night { get; set; }
public string Description { get; set; }
}
Till date I'm familiar with using JSON.net for serialize and deserialize C# objects to JSON which has exact same structure.
If you just want to populate an instance of WeatherForecast, you could use a few SelectToken calls on a plain JObject:
var parsed = JObject.Parse(json);
var forecast = new WeatherForeCast();
forecast.City = parsed.SelectToken("city.name").Value<string>();
forecast.Day = parsed.SelectToken("list[0].temp.day").Value<decimal>();
forecast.Description = parsed.SelectToken("list[0].weather[0].description").Value<string>();
forecast.Min = parsed.SelectToken("list[0].temp.min").Value<decimal>();
forecast.Max = parsed.SelectToken("list[0].temp.max").Value<decimal>();
forecast.Night = parsed.SelectToken("list[0].temp.night").Value<decimal>();
Note that this is pretty brittle though, it's making assumptions about the contents of the JSON. If the JSON changes, the path to various properties in SelectToken will be incorrect and this code will throw an exception.
Use json2csharp.com to generate your classes.
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Sys
{
public int population { get; set; }
}
public class City
{
public int id { get; set; }
public string name { get; set; }
public Coord coord { get; set; }
public string country { get; set; }
public int population { get; set; }
public Sys sys { get; set; }
}
public class Temp
{
public double day { get; set; }
public double min { get; set; }
public double max { get; set; }
public double night { get; set; }
public double eve { get; set; }
public double morn { 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 List
{
public int dt { get; set; }
public Temp temp { get; set; }
public double pressure { get; set; }
public int humidity { get; set; }
public List<Weather> weather { get; set; }
public double speed { get; set; }
public int deg { get; set; }
public int clouds { get; set; }
}
public class RootObject
{
public string cod { get; set; }
public double message { get; set; }
public City city { get; set; }
public int cnt { get; set; }
public List<List> list { get; set; }
}
Then use JSON.NET to deserialize into the class structure and extract the properties you want.
var jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
You now have an instance of RootObject and you can traverse it as needed to extract the specific value(s) you need.