Parse JSON object in C# - c#
I use JSON.NET and I would like to parse the following object which I get from a WebService. Can someone post an example on how to do that?
#"{""MessageType"":0,
""Message"":""Success"",
""Value"":[
{""listId"":1,
""listName"":""DemoList"",
""itemInList"":[
{
""fromDate"":""\/Date(1228946400000)\/"",
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""water"",
""creationDate"":""\/Date(1339448400000)\/"",
""typeId"":1
},
{
""fromDate"":null,
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""gala"",
""creationDate"":""\/Date(1304370000000)\/"",
""typeId"":1
}
]}
]}"
JSON Object
{
"MessageType":0,
"Message":"UserLists",
"Value":
[
{
"listId":1,
"listName":"DemoList",
"itemInList"
[
{
"fromDate":"\/Date(1228946400000)\/",
"fromLocation":null,
"toLocation":null,
"originalRequest":"water",
"creationDate":"\/Date(1339448400000)\/",
"typeId":1
},
{
"fromDate":null,
"fromLocation":null,
"toLocation":null,
"originalRequest":"gala",
"creationDate":"\/Date(1304370000000)\/",
"typeId":1
}
],
"numberOfItems":2
}
]
}
Thanks.
You need to create some entity like this:
public class Entity
{
public int MessageType { get; set; }
public string Message { get; set; }
public List<EntityValue> Value { get; set; }
}
public class EntityValue
{
public int listId { get; set; }
public string listName { get; set; }
public List<ItemInList> itemInList { get; set; }
}
public class ItemInList
{
public DateTime? fromDate { get; set; }
public string fromLocation { get; set; }
public string toLocation { get; set; }
public string originalRequest { get; set; }
public DateTime creationDate { get; set; }
public int typeId { get; set; }
}
The entity must has the same structure like the json data.
And you can call the Method:
JsonConvert.DeserializeObject<Entity>(json);
If it has any exception,you need to adjust the entities until it works.
Please read the below link for parsi in metro style application.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh770287.aspx
Related
How to generate a JSON class with dynamic name
I don't know if there is an existing name for that case, but I'm trying to retrieve data from NASA API (https://api.nasa.gov/) and I have a simple challenge to catch a list of objects near earth. Here is the JSON response I have from the GET request I do to "https://api.nasa.gov/neo/rest/v1/feed?...." { "links": { "next": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-04&end_date=2021-07-04&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym", "prev": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-02&end_date=2021-07-02&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym", "self": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-03&end_date=2021-07-03&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym" }, "element_count": 6, "near_earth_objects": { "2021-07-03": [ { "links": { "self": "http://www.neowsapp.com/rest/v1/neo/3701710?api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym" }, "id": "3701710", "neo_reference_id": "3701710", "name": "(2014 WF497)", "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3701710", "absolute_magnitude_h": 20.23, "estimated_diameter": { "kilometers": { } And that's the way it is built in Visual Studio (using the Special Paste option for JSON) public class NearEarthObject { public Links links { get; set; } public int element_count { get; set; } public Near_Earth_Objects near_earth_objects { get; set; } } public class Links { public string next { get; set; } public string prev { get; set; } public string self { get; set; } } public class Near_Earth_Objects { public _20210703[] _20210703 { get; set; } } public class _20210703 { public Links1 links { get; set; } public string id { get; set; } public string neo_reference_id { get; set; } public string name { get; set; } public string nasa_jpl_url { get; set; } public float absolute_magnitude_h { get; set; } public Estimated_Diameter estimated_diameter { get; set; } public bool is_potentially_hazardous_asteroid { get; set; } public Close_Approach_Data[] close_approach_data { get; set; } public bool is_sentry_object { get; set; } } The question is, inside of the element "near_earth_objects", there is an element called "2021-07-03" (the date of the data I requested), the problem is that I am trying to include it into a DataGridView made in .NET C# (Windows Forms, but that doesn't matters here, I think) and the user wants to get the information by date. So, "2021-07-03" is a valid member just for one day, and the user should be able to get data from multiple days. So, is there a way in C# to get all child objects inside of near_earth_objects without knowing their names since there will be the option to search for asteroids from date X to Y in my application?
Using System.Text.Json The API response will map to the following classes public class Neo { public Links Links { get; set; } public int ElementCount { get; set; } public Dictionary<string, List<NearEarthObject>> NearEarthObjects { get; set; } } public class Links { public string Next { get; set; } public string Prev { get; set; } public string Self { get; set; } } public class NearEarthObject { public Links Links { get; set; } public string Id { get; set; } public string Name { get; set; } // Other properties } The NearEarthObjects is simply a Dictionary, where the key is the formatted date and value is a List containing NearEarthObject The PropertyNamingPolicy will allow us to support the API's underscore property naming convention. public class UnderscoreNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) { return name.Underscore(); } } Example usage // using using System.Text.Json; var response = await new HttpClient().GetStringAsync(url); var neo = JsonSerializer.Deserialize<Neo>(response, new JsonSerializerOptions { PropertyNamingPolicy = new UnderscoreNamingPolicy() }); foreach(var neos in neo.NearEarthObjects) { Console.WriteLine(neos.Key); }
use System.Text.Json, JsonNamingPolicy demo code public class DynamicNamePolicy : JsonNamingPolicy { public override string ConvertName(string name) { var today = DateTime.Today.ToString("yyyy-MM-dd"); if (name.Equals("DateData")) //model property name return today; //convert to json string property name return name; } } //data deserialize string data = ""; //json string var obj = JsonSerializer.Deserialize<NearEarthObject>(data, new JsonSerializerOptions { PropertyNamingPolicy = new DynamicNamePolicy(), });
Not able validate data condition based on the json element attribute value from a json using c#
I have a json file, where i have to validate a json attribute element value based on another json element attribute value. But if there json elements with the same name. It always takes the last value always instead of parsing the json data fully. Please guide me. Below the sample json file { "PLMXML":{ "language":"en-us", "author":"Developer", "date":"2020-05-22", "traverseRootRefs":"#id6", "Operation":{ "id":"id21", "subType":"BS4_BaOP", "catalogueId":"70700000209604" }, "Operation":{ "id":"id28", "subType":"BS4_BaOP", "catalogueId":"70700000209603" }, "OperationRevision":{ "id":"id6", "subType":"BS4_BaOPRevision", "masterRef":"#id21", "revision":"A1" } } } And below the code which im trying to use public void Readjsonfile(string jsondata) { var message = JsonConvert.DeserializeObject<plmxmldatamodel>(jsondata); if (String.Equals(message.PLMXML.traverseRootRefs.Substring(1), message.PLMXML.OperationRevision.id)) { Console.WriteLine("Condtion1"); if (String.Equals(message.PLMXML.OperationRevision.masterRef.Substring(1), message.PLMXML.Operation.id)) { Console.WriteLine("Condition_2"); //Do something based on the condtion } } } public class Operation { public string id { get; set; } public string subType { get; set; } public string catalogueId { get; set; } } public class OperationRevision { public string id { get; set; } public string subType { get; set; } public string masterRef { get; set; } } public class PLMXML { public string language { get; set; } public string author { get; set; } public string date { get; set; } public string traverseRootRefs { get; set; } public Operation Operation { get; set; } public OperationRevision OperationRevision { get; set; } } public class plmxmldatamodel { public PLMXML PLMXML { get; set; } } When i try to dedug this in the second if condtion, the value for message.PLMXML.Operation.id is always id28 , because of which second if condition fails. While the first if condition is passed as there is only one message.PLMXML.OperationRevision.id. i wanted behaviour where it would check complete json data and check if message.PLMXML.Operation.id with value id21 is present or not , So my data gets passed. Please kindly guide me here.I am very new to C# here.
From my observation you have couple of issues. What happen you have double keys, and your parser taking the last value not the first one. First of all your json should be corrected. I assume you have access to change your json and operation should be an array like follow: { "PLMXML":{ "language":"en-us", "author":"Developer", "date":"2020-05-22", "traverseRootRefs":"#id6", "Operations":[ { "id":"id21", "subType":"BS4_BaOP", "catalogueId":"70700000209604" }, { "id":"id28", "subType":"BS4_BaOP", "catalogueId":"70700000209603" } ], "OperationRevision":{ "id":"id6", "subType":"BS4_BaOPRevision", "masterRef":"#id21", "revision":"A1" } } } When array in place than use an online tool like to validate your json and use this tool to create a model. Your model will be like this: public partial class PlmxmlDataModel { [JsonProperty("PLMXML")] public Plmxml Plmxml { get; set; } } public partial class Plmxml { [JsonProperty("language")] public string Language { get; set; } [JsonProperty("author")] public string Author { get; set; } [JsonProperty("date")] public DateTimeOffset Date { get; set; } [JsonProperty("traverseRootRefs")] public string TraverseRootRefs { get; set; } [JsonProperty("Operations")] public Operation[] Operations { get; set; } [JsonProperty("OperationRevision")] public OperationRevision OperationRevision { get; set; } } public partial class OperationRevision { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("subType")] public string SubType { get; set; } [JsonProperty("masterRef")] public string MasterRef { get; set; } [JsonProperty("revision")] public string Revision { get; set; } } public partial class Operation { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("subType")] public string SubType { get; set; } [JsonProperty("catalogueId")] public string CatalogueId { get; set; } } And your method like this: public void Readjsonfile(string jsondata) { var message = JsonConvert.DeserializeObject<PlmxmlDataModel>(jsondata); if (String.Equals(message.Plmxml.TraverseRootRefs.Substring(1), message.Plmxml.OperationRevision.Id)) { Console.WriteLine("Condtion1"); if (String.Equals(message.Plmxml.OperationRevision.MasterRef.Substring(1), message.Plmxml.Operations[0].Id)) { Console.WriteLine("Condition_2"); //Do something based on the condtion } } } Now in your method I am looking for array index 0 with contain id 28, but if you are look for id 28 in any of the array then you can do some thing like: if (message.Plmxml.Operations.Any(e => e.Id == message.Plmxml.OperationRevision.MasterRef.Substring(1)))
JSON invalid format
I'm trying to deserialize the JSON from the weather API, I have created C# classes but I can't seem to get it working. Most sites display this JSON as invalid format, so I'm not really sure whats wrong with it. Here is the JSON string and my class for Deserializing.Visual studio displays it like any other regular JSON. "[\"cod\":\"200\",\"message\":0,\"cnt\":40,\"list\":[[\"dt\":1574175600,\"main\":[\"temp\":284.79,\"temp_min\":282.63,\"temp_max\":284.79,\"pressure\":1021,\"sea_level\":1021,\"grnd_level\":958,\"humidity\":88,\"temp_kf\":2.16],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3,\"deg\":51],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-19 15:00:00\"],[\"dt\":1574186400,\"main\":[\"temp\":282.92,\"temp_min\":281.3,\"temp_max\":282.92,\"pressure\":1021,\"sea_level\":1021,\"grnd_level\":958,\"humidity\":94,\"temp_kf\":1.62],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.93,\"deg\":53],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-19 18:00:00\"],[\"dt\":1574197200,\"main\":[\"temp\":282.6,\"temp_min\":281.52,\"temp_max\":282.6,\"pressure\":1021,\"sea_level\":1021,\"grnd_level\":957,\"humidity\":93,\"temp_kf\":1.08],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.84,\"deg\":64],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-19 21:00:00\"],[\"dt\":1574208000,\"main\":[\"temp\":281.67,\"temp_min\":281.13,\"temp_max\":281.67,\"pressure\":1020,\"sea_level\":1020,\"grnd_level\":956,\"humidity\":94,\"temp_kf\":0.54],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.83,\"deg\":65],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-20 00:00:00\"],[\"dt\":1574218800,\"main\":[\"temp\":280.97,\"temp_min\":280.97,\"temp_max\":280.97,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":96,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.9,\"deg\":57],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-20 03:00:00\"],[\"dt\":1574229600,\"main\":[\"temp\":280.72,\"temp_min\":280.72,\"temp_max\":280.72,\"pressure\":1016,\"sea_level\":1016,\"grnd_level\":953,\"humidity\":96,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":90],\"wind\":[\"speed\":3.65,\"deg\":65],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-20 06:00:00\"],[\"dt\":1574240400,\"main\":[\"temp\":282.34,\"temp_min\":282.34,\"temp_max\":282.34,\"pressure\":1015,\"sea_level\":1015,\"grnd_level\":953,\"humidity\":91,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":1.32,\"deg\":78],\"rain\":[\"3h\":1.19],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-20 09:00:00\"],[\"dt\":1574251200,\"main\":[\"temp\":283.44,\"temp_min\":283.44,\"temp_max\":283.44,\"pressure\":1015,\"sea_level\":1015,\"grnd_level\":952,\"humidity\":87,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.16,\"deg\":79],\"rain\":[\"3h\":1.94],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-20 12:00:00\"],[\"dt\":1574262000,\"main\":[\"temp\":282.5,\"temp_min\":282.5,\"temp_max\":282.5,\"pressure\":1015,\"sea_level\":1015,\"grnd_level\":952,\"humidity\":90,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.21,\"deg\":75],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-20 15:00:00\"],[\"dt\":1574272800,\"main\":[\"temp\":281.27,\"temp_min\":281.27,\"temp_max\":281.27,\"pressure\":1016,\"sea_level\":1016,\"grnd_level\":953,\"humidity\":88,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"]],\"clouds\":[\"all\":80],\"wind\":[\"speed\":1.94,\"deg\":105],\"rain\":[\"3h\":0.38],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-20 18:00:00\"],[\"dt\":1574283600,\"main\":[\"temp\":280.14,\"temp_min\":280.14,\"temp_max\":280.14,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":90,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"]],\"clouds\":[\"all\":0],\"wind\":[\"speed\":1.72,\"deg\":131],\"rain\":[\"3h\":0.19],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-20 21:00:00\"],[\"dt\":1574294400,\"main\":[\"temp\":279.7,\"temp_min\":279.7,\"temp_max\":279.7,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":89,\"temp_kf\":0],\"weather\":[[\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"]],\"clouds\":[\"all\":0],\"wind\":[\"speed\":1.53,\"deg\":122],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-21 00:00:00\"],[\"dt\":1574305200,\"main\":[\"temp\":279.29,\"temp_min\":279.29,\"temp_max\":279.29,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":89,\"temp_kf\":0],\"weather\":[[\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"]],\"clouds\":[\"all\":0],\"wind\":[\"speed\":1.71,\"deg\":110],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-21 03:00:00\"],[\"dt\":1574316000,\"main\":[\"temp\":278.99,\"temp_min\":278.99,\"temp_max\":278.99,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":90,\"temp_kf\":0],\"weather\":[[\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"]],\"clouds\":[\"all\":0],\"wind\":[\"speed\":1.76,\"deg\":106],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-21 06:00:00\"],[\"dt\":1574326800,\"main\":[\"temp\":284.12,\"temp_min\":284.12,\"temp_max\":284.12,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":71,\"temp_kf\":0],\"weather\":[[\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"]],\"clouds\":[\"all\":0],\"wind\":[\"speed\":1.91,\"deg\":94],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-21 09:00:00\"],[\"dt\":1574337600,\"main\":[\"temp\":286.38,\"temp_min\":286.38,\"temp_max\":286.38,\"pressure\":1016,\"sea_level\":1016,\"grnd_level\":953,\"humidity\":62,\"temp_kf\":0],\"weather\":[[\"id\":801,\"main\":\"Clouds\",\"description\":\"few clouds\",\"icon\":\"02d\"]],\"clouds\":[\"all\":21],\"wind\":[\"speed\":2.19,\"deg\":66],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-21 12:00:00\"],[\"dt\":1574348400,\"main\":[\"temp\":282.01,\"temp_min\":282.01,\"temp_max\":282.01,\"pressure\":1016,\"sea_level\":1016,\"grnd_level\":953,\"humidity\":91,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.67,\"deg\":46],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-21 15:00:00\"],[\"dt\":1574359200,\"main\":[\"temp\":280.86,\"temp_min\":280.86,\"temp_max\":280.86,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":94,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":86],\"wind\":[\"speed\":2.78,\"deg\":49],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-21 18:00:00\"],[\"dt\":1574370000,\"main\":[\"temp\":280.55,\"temp_min\":280.55,\"temp_max\":280.55,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":92,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.52,\"deg\":56],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-21 21:00:00\"],[\"dt\":1574380800,\"main\":[\"temp\":280.04,\"temp_min\":280.04,\"temp_max\":280.04,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":953,\"humidity\":95,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.6,\"deg\":53],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-22 00:00:00\"],[\"dt\":1574391600,\"main\":[\"temp\":280.1,\"temp_min\":280.1,\"temp_max\":280.1,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":953,\"humidity\":96,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.54,\"deg\":49],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-22 03:00:00\"],[\"dt\":1574402400,\"main\":[\"temp\":281.29,\"temp_min\":281.29,\"temp_max\":281.29,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":953,\"humidity\":97,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":2.24,\"deg\":38],\"rain\":[\"3h\":0.44],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-22 06:00:00\"],[\"dt\":1574413200,\"main\":[\"temp\":280.84,\"temp_min\":280.84,\"temp_max\":280.84,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":93,\"temp_kf\":0],\"weather\":[[\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.21,\"deg\":33],\"rain\":[\"3h\":3.88],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-22 09:00:00\"],[\"dt\":1574424000,\"main\":[\"temp\":279.71,\"temp_min\":279.71,\"temp_max\":279.71,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":93,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.37,\"deg\":41],\"rain\":[\"3h\":2.81],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-22 12:00:00\"],[\"dt\":1574434800,\"main\":[\"temp\":278.48,\"temp_min\":278.48,\"temp_max\":278.48,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":93,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.59,\"deg\":49],\"rain\":[\"3h\":1.88],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-22 15:00:00\"],[\"dt\":1574445600,\"main\":[\"temp\":278.11,\"temp_min\":278.11,\"temp_max\":278.11,\"pressure\":1019,\"sea_level\":1019,\"grnd_level\":955,\"humidity\":93,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.55,\"deg\":49],\"rain\":[\"3h\":0.81],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-22 18:00:00\"],[\"dt\":1574456400,\"main\":[\"temp\":278.1,\"temp_min\":278.1,\"temp_max\":278.1,\"pressure\":1019,\"sea_level\":1019,\"grnd_level\":955,\"humidity\":93,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.67,\"deg\":49],\"rain\":[\"3h\":1.38],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-22 21:00:00\"],[\"dt\":1574467200,\"main\":[\"temp\":277.43,\"temp_min\":277.43,\"temp_max\":277.43,\"pressure\":1020,\"sea_level\":1020,\"grnd_level\":955,\"humidity\":93,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.15,\"deg\":47],\"rain\":[\"3h\":0.75],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-23 00:00:00\"],[\"dt\":1574478000,\"main\":[\"temp\":277.23,\"temp_min\":277.23,\"temp_max\":277.23,\"pressure\":1019,\"sea_level\":1019,\"grnd_level\":955,\"humidity\":92,\"temp_kf\":0],\"weather\":[[\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"]],\"clouds\":[\"all\":98],\"wind\":[\"speed\":3.5,\"deg\":59],\"rain\":[\"3h\":0.56],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-23 03:00:00\"],[\"dt\":1574488800,\"main\":[\"temp\":276.54,\"temp_min\":276.54,\"temp_max\":276.54,\"pressure\":1020,\"sea_level\":1020,\"grnd_level\":955,\"humidity\":95,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":98],\"wind\":[\"speed\":3.32,\"deg\":59],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-23 06:00:00\"],[\"dt\":1574499600,\"main\":[\"temp\":278.93,\"temp_min\":278.93,\"temp_max\":278.93,\"pressure\":1019,\"sea_level\":1019,\"grnd_level\":955,\"humidity\":86,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.36,\"deg\":56],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-23 09:00:00\"],[\"dt\":1574510400,\"main\":[\"temp\":280.06,\"temp_min\":280.06,\"temp_max\":280.06,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":80,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.74,\"deg\":53],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-23 12:00:00\"],[\"dt\":1574521200,\"main\":[\"temp\":277.41,\"temp_min\":277.41,\"temp_max\":277.41,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":954,\"humidity\":89,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.84,\"deg\":55],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-23 15:00:00\"],[\"dt\":1574532000,\"main\":[\"temp\":276.83,\"temp_min\":276.83,\"temp_max\":276.83,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":92,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":96],\"wind\":[\"speed\":3.75,\"deg\":56],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-23 18:00:00\"],[\"dt\":1574542800,\"main\":[\"temp\":277.04,\"temp_min\":277.04,\"temp_max\":277.04,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":90,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":100],\"wind\":[\"speed\":3.55,\"deg\":61],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-23 21:00:00\"],[\"dt\":1574553600,\"main\":[\"temp\":275.99,\"temp_min\":275.99,\"temp_max\":275.99,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":96,\"temp_kf\":0],\"weather\":[[\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":81],\"wind\":[\"speed\":3.19,\"deg\":55],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-24 00:00:00\"],[\"dt\":1574564400,\"main\":[\"temp\":276.56,\"temp_min\":276.56,\"temp_max\":276.56,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":953,\"humidity\":96,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"]],\"clouds\":[\"all\":91],\"wind\":[\"speed\":3.02,\"deg\":62],\"sys\":[\"pod\":\"n\"],\"dt_txt\":\"2019-11-24 03:00:00\"],[\"dt\":1574575200,\"main\":[\"temp\":277.36,\"temp_min\":277.36,\"temp_max\":277.36,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":95,\"temp_kf\":0],\"weather\":[[\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":86],\"wind\":[\"speed\":2.99,\"deg\":62],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-24 06:00:00\"],[\"dt\":1574586000,\"main\":[\"temp\":280.51,\"temp_min\":280.51,\"temp_max\":280.51,\"pressure\":1018,\"sea_level\":1018,\"grnd_level\":954,\"humidity\":82,\"temp_kf\":0],\"weather\":[[\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04d\"]],\"clouds\":[\"all\":74],\"wind\":[\"speed\":3.05,\"deg\":64],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-24 09:00:00\"],[\"dt\":1574596800,\"main\":[\"temp\":282.87,\"temp_min\":282.87,\"temp_max\":282.87,\"pressure\":1016,\"sea_level\":1016,\"grnd_level\":953,\"humidity\":74,\"temp_kf\":0],\"weather\":[[\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03d\"]],\"clouds\":[\"all\":42],\"wind\":[\"speed\":3.21,\"deg\":50],\"sys\":[\"pod\":\"d\"],\"dt_txt\":\"2019-11-24 12:00:00\"]],\"city\":[\"id\":787657,\"name\":\"Nis\",\"coord\":[\"lat\":43.3247,\"lon\":21.9033],\"country\":\"RS\",\"timezone\":3600,\"sunrise\":1574141412,\"sunset\":1574175927]]" And my class for deserializing: public class WeatherInfo { public class root { public string cod { get; set; } public string message { get; set; } public string cnt { get; set; } public allLists list { get; set; } public city city { get; set; } } public class allLists { allinfo[] allinfos { get; set; } } public class allinfo { public string dt { get; set; } public main main { get; set; } public allWeathers weather { get; set; } public string dt_txt { get; set; } } public class main { public double temp { get; set; } public double temp_min { get; set; } public double temp_max { get; set; } public double pressure { get; set; } public double sea_level { get; set; } public double grnd_level { get; set; } public double humidity { get; set; } public double temp_kf { get; set; } } public class allWeathers { public weather[] weathers { 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 clouds { public double all { get; set; } } public class wind { public double speed { get; set; } public double deg { get; set; } } public class sys { public string pod { 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 string timezone { get; set; } public string sunrise { get; set; } public string sunset { get; set; } } public class coord { public double lat { get; set; } public double lon { get; set; } } }
Your JSON is not valid. The main thing is that you are using brackets [] where you should be using braces {}. In JSON [] is an array, while {} is an object. There are a couple of places where you need to have an array (e.g. list) so you can't simply do a find-replace to fix this. An easy way to resolve this in the future is to create an instance of your WeatherInfo class, populate it with data, and then serialize it to JSON. You can then compare that with the JSON you have (using a diff tool like KDiff or WinMerge) to identify where your source JSON is different from your generated JSON.
A valid JSON always starts with a [ or a { and ends with the same, where square bracket [ represents an array and curly bracket { represents an object. Looking at your C# class, your JSON lacks the curly brace to start with for objects and is also missing names for the arrays like allinfos. You should start building your JSON like this: var json = JToken.Parse ("{\"cod\":\"200\",\"message\":0,\"cnt\":40,\"list\":{\"allinfos\":[{\"dt\":1574175600, \"main\":{\"temp\":284.79,\"temp_min\":282.63,\"temp_max\":284.79,\"pressure\":1021,\"sea_level\":1021,\"grnd_level\":958,\"humidity\":88,\"temp_kf\":2.16}}]}}").ToString(Formatting.Indented); This will give a formatted, easy to read output like this: { "cod": "200", "message": 0, "cnt": 40, "list": { "allinfos": [ { "dt": 1574175600, "main": { "temp": 284.79, "temp_min": 282.63, "temp_max": 284.79, "pressure": 1021, "sea_level": 1021, "grnd_level": 958, "humidity": 88, "temp_kf": 2.16 } } ] } }
Update: The JSON was actually valid, the problem is that I was trying to work with debugging version of the string. The debugger automatically adds escape characters and "" quotes. Also some of the classes I had didn't follow up the JSON format correctly, so that error stopped me from seeing the real issue here.
Json.Net deserialize JSON objects
I've popped consuming a WebServer returning the Json bellow, and I'm not able to convert it to an object. Json { "success":true, "data":{ "24486146360":{ "rfid":"123465789456", "products":[ { "sale_id":35, "quantity":2, "price":"1", "total":"2", "unit":"uni", "sku":14 }, { "sale_id":36, "quantity":2, "price":"2.5", "total":"5", "unit":"uni", "sku":17 } ] }, "24758345953":{ "rfid":"2129", "products":[ { "sale_id":39, "quantity":1, "price":"10", "total":"10", "unit":"ml", "sku":19998 } ] }, "64577015900":{ "rfid":"1934", "products":[ { "sale_id":40, "quantity":1, "price":"10", "total":"10", "unit":"ml", "sku":19998 } ] }, "56768990934":{ "rfid":"1746", "products":[ { "sale_id":46, "quantity":1, "price":"8.00", "total":"8", "unit":"UN", "sku":20 } ] } } } I used json2sharp to generate a class from the JSON, I then cleaned up the class and was left with the following: My Class create help for json2sharp public class Consumo { public string rfid { get; set; } public List<ConsumoProduto> products { get; set; } } public class ConsumoProduto { public int sale_id { get; set; } public double quantity { get; set; } public string price { get; set; } public string total { get; set; } public string unit { get; set; } public int sku { get; set; } } public class RetornoConsumo { [JsonProperty("success")] public bool Processado { get; set; } [JsonProperty("data")] public List<Consumo> Registro { get; set; } } My Problem how do I convert Json to a valid object using Json.Net? Test I tried to do this and I could not Dictionary<string, RetornoConsumo> _featuredArticles = JsonConvert.DeserializeObject<Dictionary<string, RetornoConsumo>>(json);
In your RetornoConsumo class, the Registro property needs to be a Dictionary<string, Consumo> not a List<Consumo>. public class RetornoConsumo { [JsonProperty("success")] public bool Processado { get; set; } [JsonProperty("data")] public Dictionary<string, Consumo> Registro { get; set; } } Then, you need to deserialize the JSON into the RetornoConsumo class: var data = JsonConvert.DeserializeObject<RetornoConsumo>(json); Fiddle: https://dotnetfiddle.net/vfhdXp
Can't deserialize JSON from REST API (Wordpress) using RestSharp
This has been driving me nuts - I can't deserialize some JSON I'm getting back from the Wordpress public API to get my posts. I'm using RestSharp. The data I'm getting back shows a blog post, but all the properties are null. I even used Json2CSharp to model my "Post" class after what's returned. Here's my JSON: { "found":1, "posts":[ { "ID":2, "site_ID":89749867, "author":{ "ID":2988648, "login":"loginname", "email":false, "name":"loginname", "nice_name":"loginname", "URL":"", "avatar_URL":"https:\/\/2.gravatar.com\/avatar\/e78ee2e2f7bb75a8bc5339a6bd20194e?s=96&d=identicon&r=G", "profile_URL":"http:\/\/en.gravatar.com\/loginname", "site_ID":2918427 }, "date":"2015-04-20T18:16:18+00:00", "modified":"2015-04-20T18:18:20+00:00", "title":"Hello world!", "URL":"https:\/\/myblog.wordpress.com\/2015\/04\/20\/hello-world\/", "short_URL":"http:\/\/wp.me\/p64A2v-2", "content":"<p><a href=\"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png\"><img class=\"alignnone size-medium wp-image-3\" src=\"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png?w=300&h=180\" alt=\"Left Shark\" width=\"300\" height=\"180\" \/><\/a><\/p>\n<p>This is your very first post. Click the Edit link to modify or delete it, or <a title=\"Direct link to Add New Post in your Dashboard\" href=\"https:\/\/wordpress.com\/post\">start a new post<\/a>. If you like, use this post to tell readers why you started this blog and what you plan to do with it.<\/p>\n<p>Happy blogging!<\/p>\n", "excerpt":"<p>This is your very first post. Click the Edit link to modify or delete it, or start a new post. If you like, use this post to tell readers why you started this blog and what you plan to do with it. Happy blogging!<\/p>\n", "slug":"hello-world", "guid":"http:\/\/myblog.wordpress.com\/?p=1", "status":"publish", "sticky":false, "password":"", "parent":false, "type":"post", "discussion":{ "comments_open":true, "comment_status":"open", "pings_open":true, "ping_status":"open", "comment_count":0 }, "likes_enabled":true, "sharing_enabled":true, "like_count":0, "i_like":0, "is_reblogged":0, "is_following":0, "global_ID":"7a5ad608c4e80f7c2463eead8d34f435", "featured_image":"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png", "post_thumbnail":{ "ID":3, "URL":"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png", "guid":"http:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png", "mime_type":"image\/png", "width":620, "height":372 }, "format":"standard", "geo":false, "menu_order":0, "page_template":"", "publicize_URLs":[ ], "tags":{ }, "categories":{ "Uncategorized":{ "ID":1, "name":"Uncategorized", "slug":"uncategorized", "description":"", "post_count":1, "parent":0, "meta":{ "links":{ "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/categories\/slug:uncategorized", "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/categories\/slug:uncategorized\/help", "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867" } } } }, "attachments":{ "3":{ "ID":3, "URL":"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png", "guid":"http:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png", "date":"2015-04-20T18:17:33+00:00", "post_ID":2, "file":"left_shark_5x3.png", "mime_type":"image\/png", "extension":"png", "title":"Left Shark", "caption":"", "description":"", "alt":"Left Shark", "thumbnails":{ }, "height":372, "width":620, "exif":{ "aperture":0, "credit":"", "camera":"", "caption":"", "created_timestamp":0, "copyright":"", "focal_length":0, "iso":0, "shutter_speed":0, "title":"", "orientation":0 }, "meta":{ "links":{ "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/media\/3", "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/media\/3\/help", "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867", "parent":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2" } } } }, "attachment_count":1, "metadata":[ { "id":"9", "key":"_thumbnail_id", "value":"3" } ], "meta":{ "links":{ "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2", "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2\/help", "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867", "replies":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2\/replies\/", "likes":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2\/likes\/" } }, "capabilities":{ "publish_post":false, "delete_post":false, "edit_post":false } } ] } Here's my class (with some properties commented out so I didn't have to build those out: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace thenickwilson_SPA_NEW.Models { public class Post { public int ID { get; set; } public int site_ID { get; set; } //public Author author { get; set; } public string date { get; set; } public string modified { get; set; } public string title { get; set; } public string URL { get; set; } public string short_URL { get; set; } public string content { get; set; } public string excerpt { get; set; } public string slug { get; set; } public string guid { get; set; } public string status { get; set; } public bool sticky { get; set; } public string password { get; set; } public bool parent { get; set; } public string type { get; set; } //public Discussion discussion { get; set; } public bool likes_enabled { get; set; } public bool sharing_enabled { get; set; } public int like_count { get; set; } public int i_like { get; set; } public int is_reblogged { get; set; } public int is_following { get; set; } public string global_ID { get; set; } public string featured_image { get; set; } //public PostThumbnail post_thumbnail { get; set; } public string format { get; set; } public bool geo { get; set; } public int menu_order { get; set; } public string page_template { get; set; } public List<object> publicize_URLs { get; set; } //public Tags tags { get; set; } //public Categories categories { get; set; } //public Attachments attachments { get; set; } public int attachment_count { get; set; } //public List<Metadata> metadata { get; set; } //public Meta3 meta { get; set; } //public Capabilities capabilities { get; set; } } } And here's the rest of my code: [ResponseType(typeof(Post))] public IHttpActionResult Get() { var client = new RestClient("http://public-api.wordpress.com/rest/v1.1/"); var request = new RestRequest("sites/{id}/posts", Method.GET); request.AddUrlSegment("id", "myblog.wordpress.com"); request.RequestFormat = DataFormat.Json; var response = client.Execute<List<Post>>(request); return this.Ok(response); } I have a feeling it has to do with the fact that the API returns a "found" element as well as "posts", but I'm not sure. Any help would be greatly appreciated.
You are receiving an array or list of Posts wrapped in a container object, so try with this: public class MyContainer { public List<Post> posts {get;set;} } And: var response = client.Execute<MyContainer>(request); You can view your json deserialized here: http://jsonviewer.stack.hu/