Monday, October 1, 2012

Difficulty with json string deserialization

Difficulty with json string deserialization

I make a web request in Silverlight for windows phone. And this is the responce.

{"result": { "account": null, "checkInfo": null, "command": null, "shifts": [     {         "description": "17:45 - 17:55 work shift",         "id": 5459,         "venueId": 132     }]} 

I use Newtonsoft.Json.dll and my purpose is to catch the array - shifts.

JObject obj = JObject.Parse(StringShifts); JArray sh = (JArray)obj["shifts"]; 

But every time sh value is null. What i'm i doing wrong? Thank you in advance.

Answers & Comments...

Answer: 1
var obj = (JObject)JsonConvert.DeserializeObject(json); foreach (var shift in obj["result"]["shifts"]) {     Console.WriteLine((string)shift["description"]); } 
by : L.Bhttp://stackoverflow.com/users/932418

Answer: 2

You are missing the root results node; this is how you should use it:

JArray sh = (JArray)obj["result"]["shifts"]; 

Also, do note that there is a missing } in the end of your JSON sample above!

by : Pedro Lamashttp://stackoverflow.com/users/358596

Answer: 3

The other way around is: (This is very helpful, if you are doing more operations like this in your project)
Create these classes in your project

public class Shift     {         public string description { get; set; }         public int id { get; set; }         public int venueId { get; set; }     }      public class Result     {         public object account { get; set; }         public object checkInfo { get; set; }         public object command { get; set; }         public List<Shift> shifts { get; set; }     }      public class RootObject     {         public Result result { get; set; }     } 

And then in your code

 var rootObject = JsonConvert.DeserializeObject<RootObject>(StringShifts);  foreach(var shift in rootObject.result.shifts)  {      Console.Write(shift.description);  } 

This way you can have more control on your json response data. But L.B 's answer if it is one time process in your app.

by : nkchandrahttp://stackoverflow.com/users/649306




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog