Silverlight access an ashx JSON response
Use System.Json to load the string into a JsonArray. JsonValue.Load() takes a response stream and can populate a JsonArray - from there, you can either iterate through or use LINQ to query the values.
Links:
Thanks for the reply Jon. Your links helped me figure it out and I thought I should include the code I used in this question for others that come across this question in the future.
Two ways of handling the Json. For both methods you need to setup a handler to get the Json data.
// This gets the URL to call to get the Json dataUri uri = GetSomeUrl();WebClient downloader = new WebClient();downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);downloader.OpenReadAsync(uri);
You then need to implement the event handler downloader_OpenReadCompleted
specified above with the code to handle the Json. In both case the code below should be wrapped in a using statement:
using (System.IO.Stream strResult = e.Result){}
First way to handle the Json data that is part of the Silverlight framework is to add a reference to System.Json
.
JsonArray jsonArray = (JsonArray)JsonArray.Load(e.Result);List<SomeObject> lst = new List<SomeObject>();foreach (System.Json.JsonObject obj in jsonArray){ SomeObject obj = new SomeObject(); obj.ID = int.Parse(obj["ID"].ToString(); obj.Description = obj["Description"].ToString(); obj.Value = double.Parse(obj["Value"].ToString()); lst.Add(obj);}
The other way that is possible with or without Silverlight is:
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<SomeObject>));List<SomeObject> lst = (List<SomeObject>)(serializer.ReadObject(strResult));
Both methods end up getting me a list of my objects which I can then use as I see fit.
Thanks for the help Jon!