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();
}
Related
I have this Json:
{
"trades": [
{
"id": "4004",
"instrument": "EUR_USD",
"price": "1.08938",
"openTime": "2020-02-26T12:15:32.309973340Z",
"initialUnits": "1",
"initialMarginRequired": "0.0363",
"state": "OPEN",
"currentUnits": "1",
"realizedPL": "0.0000",
"financing": "0.0000",
"dividendAdjustment": "0.0000",
"unrealizedPL": "-0.0026",
"marginUsed": "0.0362",
"takeProfitOrder": {
"id": "4005",
"createTime": "2020-02-26T12:15:32.309973340Z",
"type": "TAKE_PROFIT",
"tradeID": "4004",
"price": "1.09099",
"timeInForce": "GTC",
"triggerCondition": "DEFAULT",
"state": "PENDING"
}
}
],
"lastTransactionID": "4010"
}
And Classes:
public class TakeProfitOrder
{
public string id { get; set; }
public string createTime { get; set; }
public string type { get; set; }
public string tradeID { get; set; }
public string price { get; set; }
public string timeInForce { get; set; }
public string triggerCondition { get; set; }
public string state { get; set; }
}
public class Trade
{
public string id { get; set; }
public string instrument { get; set; }
public string price { get; set; }
public string openTime { get; set; }
public string initialUnits { get; set; }
public string initialMarginRequired { get; set; }
public string state { get; set; }
public string currentUnits { get; set; }
public string realizedPL { get; set; }
public string financing { get; set; }
public string dividendAdjustment { get; set; }
public string unrealizedPL { get; set; }
public string marginUsed { get; set; }
public TakeProfitOrder takeProfitOrder { get; set; }
}
public class RootObject
{
public List<Trade> trades { get; set; }
public string lastTransactionID { get; set; }
}
I deserialize with :
var result = JsonConvert.DeserializeObject<RootObject>(Json);
var price = result.trades.Select(p => p.price).ToList();
price.ForEach(Console.WriteLine);
It works. I can access "price" in "trades", but I do not know how to access the "price" in "takeProfitOrder". I need the value of "price" from "takeProfitOrder" in to a list. I am sure it is something very simple but I cannot figure out how to do it, even after looking at some similar examples.
Can somebody please help me?
It's simple
result.trades.Select(p => p.takeProfitOrder.price)
You should understand better from this example
foreach (Trade trade in result.trades)
{
TakeProfitOrder takeProfitOrder = trade.takeProfitOrder;
Console.WriteLine(takeProfitOrder.price);
}
I have a JSON object with a dynamic key for the properties I wish to map to a class. I'm uncertain how to build my class to deserialize with JSON.NET. I need the values from the 'results' and 'more' keys at the upper level and also the the values from the 'timesheets' key.
Here is my JSON data.
{
"results": {
"timesheets": {
"7994790": {
"id": 7994790,
"user_id": 165502,
"jobcode_id": 11267673,
"start": "2019-12-20T05:48:00-05:00",
"end": "2019-12-20T13:44:00-05:00",
"duration": 28560,
"date": "2019-12-20",
"tz": -5,
"tz_str": "tsET",
"type": "regular",
"location": "Android App",
"on_the_clock": false,
"locked": 0,
"notes": "",
"customfields": {
"20251": "",
"19647": "Laborer",
"20327": "",
"19648": ""
},
"last_modified": "2019-12-20T20:28:48+00:00",
"attached_files": [],
"created_by_user_id": 165502
},
"8087496": {
"id": 8087496,
"user_id": 165502,
"jobcode_id": 2415904,
"start": "2019-12-20T13:44:00-05:00",
"end": "2019-12-20T15:11:00-05:00",
"duration": 5220,
"date": "2019-12-20",
"tz": -5,
"tz_str": "tsET",
"type": "regular",
"location": "Android App",
"on_the_clock": false,
"locked": 0,
"notes": "",
"customfields": {
"20251": "",
"19647": "Laborer",
"20327": "",
"19648": ""
},
"last_modified": "2019-12-20T20:28:49+00:00",
"attached_files": [],
"created_by_user_id": 165502
}
}
},
"more": false
}
And my classes as I currently have them which returns this error.
System.ArgumentNullException: 'Value cannot be null.
Parameter name: values'
public class RootObject
{
public Results results { get; set; }
public bool more { get; set; }
}
public class Results
{
public Timesheets timesheets { get; set; }
}
public class Timesheets
{
public Dictionary<int, TimesheetDetails> timesheetsdetails { get; set; }
}
public class TimesheetDetails
{
public int id { get; set; }
public int user_id { get; set; }
public int jobcode_id { get; set; }
public DateTime start { get; set; }
public DateTime end { get; set; }
public int duration { get; set; }
public string date { get; set; }
public int tz { get; set; }
public string tz_str { get; set; }
public string type { get; set; }
public string location { get; set; }
public bool on_the_clock { get; set; }
public int locked { get; set; }
public string notes { get; set; }
public DateTime last_modified { get; set; }
public List<object> attached_files { get; set; }
public int created_by_user_id { get; set; }
}
var stuff = JsonConvert.DeserializeObject<RootObject>(result.Content);
Console.WriteLine(string.Join(",", stuff.results.timesheets.timesheetsdetails));
First of all your json is not valid. After the end of the first timesheet data, there should be a , You can use any json validator online simply to validate it.
And in your model the Results is not valid according to the json. The below one works for me.
public class Response
{
[JsonProperty("results")] public TimeSheetResponse TimeSheetResponse { get; set; }
[JsonProperty("more")] public bool More { get; set; }
}
public class TimeSheetResponse
{
[JsonProperty("timesheets")] public Dictionary<string, Timesheet> Timesheets { get; set; }
}
public class Timesheet
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("user_id")]
public long UserId { get; set; }
[JsonProperty("jobcode_id")]
public long JobcodeId { get; set; }
[JsonProperty("start")] public DateTimeOffset Start { get; set; }
[JsonProperty("end")] public DateTimeOffset End { get; set; }
[JsonProperty("duration")] public long Duration { get; set; }
[JsonProperty("date")] public DateTimeOffset Date { get; set; }
[JsonProperty("tz")] public long Tz { get; set; }
[JsonProperty("tz_str")] public string TzStr { get; set; }
[JsonProperty("type")] public string Type { get; set; }
[JsonProperty("location")] public string Location { get; set; }
[JsonProperty("on_the_clock")] public bool OnTheClock { get; set; }
[JsonProperty("locked")] public long Locked { get; set; }
[JsonProperty("notes")] public string Notes { get; set; }
[JsonProperty("customfields")] public Dictionary<string, string> Customfields { get; set; }
[JsonProperty("last_modified")] public DateTimeOffset LastModified { get; set; }
[JsonProperty("attached_files")] public List<object> AttachedFiles { get; set; }
[JsonProperty("created_by_user_id")]
public long CreatedByUserId { get; set; }
}
To deserialize to Object..
var timeSheetResult = JsonConvert.DeserializeObject<Response>(data);
How can I convert my json-string to class
this is my json
{
"$id": "1",
"Result": {
"$id": "2",
"dateTime": 23821964,
"list": [{
"$id": "3",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false,
"ForfeitCount": 0,
"RewardCount": 0,
"ThisCountReport": 2,
"Reported": [{
"$id": "4",
"BlockerId": 355,
"Title": "محتوای غیر اخلاقی",
"Date": -19527396,
"ForfeitCount": 0,
"RewardCount": 0
}, {
"$id": "5",
"BlockerId": 355,
"Title": "محتوای غیر مرتبط",
"Date": -19527382,
"ForfeitCount": 0,
"RewardCount": 0
}],
"Gem": 0
}, {
"$id": "6",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false
}]
},
"StatusCode": "Created",
"Description": null
}
And I do these step, but nothing happens
JObject json1 = JObject.Parse(strMyJson);
_CommentAdmindto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<_CommentAdmindto>(json1.ToString());
_CommentAdmindto deserializedProduct = JsonConvert.DeserializeObject<_CommentAdmindto>(json);
_CommentAdmindto deserializedProduct1 = ConvertJsonToClass<_CommentAdmindto>(strMyJson);
JsonSerializer serializer = new JsonSerializer();
_CommentAdmindto p = (_CommentAdmindto)serializer.Deserialize(new JTokenReader(strMyJson), typeof(_CommentAdmindto));
And here is my class and function:
public static T ConvertJsonToClass<T>( string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IQueryable<CommentDtoAdmin> list { get; set; }
}
public class CommentDtoAdmin
{
public long UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public string ProductTitle { get; set; }
public long CommentId { get; set; }
public string Logo { get; set; }
public long Date { get; set; }
public long AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
}
Your model should be similar to this (For invalid c# names, you can use JsonProperty attribute) :
public class Reported
{
[JsonProperty("$id")]
public string id { get; set; }
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class List
{
[JsonProperty("$id")]
public string id { get; set; }
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
[JsonProperty("$id")]
public string id { get; set; }
public int dateTime { get; set; }
public List<List> list { get; set; }
}
public class RootObject
{
[JsonProperty("$id")]
public string id { get; set; }
public Result Result { get; set; }
public string StatusCode { get; set; }
public object Description { get; set; }
}
Now you can deserialize as
var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);
BTW: http://json2csharp.com/ can help to guess your model when working with json.
You seem to be trying to deserialize in a lot of different ways but you don't have a full structure to actually match the json. You miss the outer class (representing the full object) and at least Newtonsoft.Json cannot deserialize to an IQueryable so I changed that to IEnumerable.
string strMyJson = "{\"$id\":\"1\",\"Result\":{\"$id\":\"2\",\"dateTime\":23826985,\"list\":[{\"$id\":\"3\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false,\"ForfeitCount\":0,\"RewardCount\":0,\"ThisCountReport\":2,\"Reported\":[{\"$id\":\"4\",\"BlockerId\":355,\"Title\":\"Ù…Øتوای غیر اخلاقی\",\"Date\":-19527396,\"ForfeitCount\":0,\"RewardCount\":0},{\"$id\":\"5\",\"BlockerId\":355,\"Title\":\"Ù…Øتوای غیر مرتبط\",\"Date\":-19527382,\"ForfeitCount\":0,\"RewardCount\":0}],\"Gem\":0},{\"$id\":\"6\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false}],\"StatusCode\":\"Created\",\"Description\":null}}";
var result = JsonConvert.DeserializeObject<Wrapper>(strMyJson);
with classes looking like this:
public class Wrapper
{
public _CommentAdmindto Result { get; set; }
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IEnumerable<CommentDtoAdmin> list { get; set; }
}
CommentDtoAdmin is looking the same.
Though I must say that this only helps you with the deserialization.
Firstly, the $id" properties are synthetic properties added by Json.NET to track and preserve multiple references to the same object. For details, see PreserveReferencesHandling setting.
Thus, if you temporarily remove the "$id" properties, you can upload your JSON to http://json2csharp.com/ and get the following data model:
public class Reported
{
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class CommentDtoAdmin
{
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
public int dateTime { get; set; }
public List<CommentDtoAdmin> list { get; set; }
}
public class RootObject
{
public Result Result { get; set; }
public string StatusCode { get; set; }
public string Description { get; set; }
}
I then modified the returned model as follows:
I used the name CommentDtoAdmin for the list type.
I set the type of the Description property to string.
Now your JSON can be deserialized and re-serialized as follows:
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var root = JsonConvert.DeserializeObject<RootObject>(json1, settings);
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);
Note that Json.NET has no built-in logic for deserializing the interface IQueryable<T> to a concrete type, so I had to leave the property as public List<CommentDtoAdmin> list { get; set; }. You can always generate a queryable from the list using AsQueryable():
var queryable = root.Result.list.AsQueryable();
Sample fiddle.
I think you json string does not have correct syntax. It looks like a ']' (end of Array) and a final '}' is missing.
That's what the Visual Studio editor told me when making a json file out of your string after removing all the '\'
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.