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.
Related
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();
}
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);
}
}
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 '\'
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.
Im having a problem deserializing some json I get from a webserver and I think it is beacuse of the formating.
The json look like this :
{
"post_count": {
"total_posts": 1,
"sfw_total_posts": 1,
"use": 0
},
"posts_per_page": 1,
"posts": [
{
"guid": 10019127,
"wp_id": 656197,
"type": "media",
"title": "Test",
"path": "TestPath",
"publish_start": 1385559021,
"author": "Test",
"web_url": "http://www.test.com",
"nsfw": "No",
"modified": 1385532803,
"video": "No",
"likes": 484,
"dislikes": 51,
"main_category_id": 71,
"thumbnails": [
{
"w": 120,
"h": 120
},
{
"w": 240,
"h": 240
}
],
"comments": 26
}
],
"server": "100.200",
"time": 0.42163896560669
}
I have created a class with the value for there that I want to use and then using
LatestChive lastchives = JsonConvert.DeserializeObject<LatestChive>(jsonstring);
I try to deserialize it but all the values return null (I only want the stuff that is in "posts")
If I try with "post_count" or "posts_per_page" i can get the values just not from the the "posts"
I hope this makes sense and there is a easy fix thank you.
Define your classes as
public class PostCount
{
public int total_posts { get; set; }
public int sfw_total_posts { get; set; }
public int use { get; set; }
}
public class Thumbnail
{
public int w { get; set; }
public int h { get; set; }
}
public class Post
{
public int guid { get; set; }
public int wp_id { get; set; }
public string type { get; set; }
public string title { get; set; }
public string path { get; set; }
public int publish_start { get; set; }
public string author { get; set; }
public string web_url { get; set; }
public string nsfw { get; set; }
public int modified { get; set; }
public string video { get; set; }
public int likes { get; set; }
public int dislikes { get; set; }
public int main_category_id { get; set; }
public List<Thumbnail> thumbnails { get; set; }
public int comments { get; set; }
}
public class LatestChive
{
public PostCount post_count { get; set; }
public int posts_per_page { get; set; }
public List<Post> posts { get; set; }
public string server { get; set; }
public double time { get; set; }
}
For your future work see http://json2csharp.com/