I already have the answer for this using silverlight’s System.JSON but specs got changed and now I need to do it in .NET 3.5
here’s the JSON I’m getting
{"SearchResults":[{"PageCount":"1"},
{"SEARCHVAL":"Result","CATEGORY":"Category1","X":"1","Y":"2"},
{"SEARCHVAL":"AnotherResult","CATEGORY":"Category1","X":"2","Y":"2"}]}
and the solution using System.JSON assembly was
var resultList = ((JsonArray)searchResults["SearchResults"])
.OfType<JsonObject>()
.Where(o => o.ContainsKey("SEARCHVAL"))
.Select(o => new SearchResult() {
SearchValue = o["SEARCHVALUE"],
Category = o["CATEGORY"].
X = o["X"],
Y = o["Y"]
}).ToList();
I figure most of the code is similar/exactly the same but I’m not sure about the ContainsKey’s counterpart in JSON.net. I think it’s the Contains() method but I’m not exactly sure how to use it so that I could get the X and Y of the SEARCHVAL.
UPDATE:
so here’s my code to get the JSON stream and parsing:
...
Uri uri = new Uri(url);
WebClient client = new WebClient();
ParseJSON(client.OpenRead(uri));
}
private void ParseJSON(Stream stream)
{
if (stream == null)
return;
StreamReader reader = new StreamReader(stream);
JObject searchResult = JObject.Parse(reader.ReadLine());
string x= searchResult["SearchResults"][0]["SEARCHVAL"]["X"].ToString();
string y= searchResult["SearchResults"][0]["SEARCHVAL"]["Y"].ToString();
// use data
...
and I’m getting a null exception on string lat = searchresult.... Any clue where I went wrong on using JSON.NET?
Here’s the working solution using JSON.NET:
Getting the json:
Parsing the stream as JObject:
the .Replace() can be disregarded if there are no unnecessary characters included on the parsed string. I was using Json.NET 3.5 so you’ll probably won’t need to do this in the most updated release.