Reputation: 308
I am trying to deserialize my JSON notation to an object. I'm getting this error: {"'Newtonsoft.Json.Linq.JProperty' does not contain a definition for 'id'"}
Here is my JSON represented in json3:
string json3 = "{'Rows':[{'id':'1017','ischecked':'true'},{'id':'1018','ischecked':'false'}]}"
Here is my c# code:
dynamic dynJson = JsonConvert.DeserializeObject(json3);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1}\n", item.id, item.ischecked);
}
Is my JSON not formed correctly? It seems like this should be pretty straight forward.
Upvotes: 1
Views: 196
Reputation: 308
Thanks Pranay, here is what I finally used. You were very close and got me down the right path. The code below works on both formats of JSON, each represented in the variables json2 and json3.
Classes:
using Newtonsoft.Json;
public class CheckBoxResultsJson
{
public List<boCheckBoxResult> checkboxes { get; set; }
}
public class boCheckBoxResult
{
public int id { get; set; }
public bool ischecked { get; set; }
}
Code to consume the JSON:
//string json2 = "{\"checkboxes\":[{\"id\":\"1018\",\"ischecked\":\"true\"},{\"id\":\"1019\",\"ischecked\":\"true\"},{\"id\":\"1020\",\"ischecked\":\"true\"},{\"id\":\"1017\",\"ischecked\":\"true\"},{\"id\":\"1021\",\"ischecked\":\"true\"},{\"id\":\"18\",\"ischecked\":\"true\"}]}";
string json3 = "{'checkboxes':[{'id':'1017','ischecked':'true'},{'id':'1018','ischecked':'false'}]}";
//CheckBoxResultsJson checkBoxResultJson = (CheckBoxResultsJson)JsonConvert.DeserializeObject(json2, typeof(CheckBoxResultsJson));
CheckBoxResultsJson checkBoxResultJson = (CheckBoxResultsJson)JsonConvert.DeserializeObject(json3, typeof(CheckBoxResultsJson));
Console.WriteLine(checkBoxResultJson.checkboxes.Count.ToString());
foreach(boCheckBoxResult x in checkBoxResultJson.checkboxes)
{
int id = x.id;
}
Upvotes: 0
Reputation: 176916
why dont you crete object like this and desrialize it
public class Row
{
public int ID { get; set; }
public bool ischecked { get; set; }
}
List<Row> list = JsonConvert.DeserializeObject<List<Row>>(stringofjson);
if it dont work than try this way
public class RowJson
{
[JsonProperty("Rows")]
public Row Row { get; set; }
}
public class Row
{
public int ID { get; set; }
public bool ischecked { get; set; }
}
List<RowJson> list = JsonConvert.DeserializeObject<List<RowJson>>(stringofjson);
Upvotes: 4