Lets explore the JSON Data consumtion example in Windows 8 application using the Flickr JSON API.
There is no WebClient class in new API, but we can make use of the HttpClient class that works in a similar way. We can also provide an asynchronous method to fetch the data.
The new HttpClient class itself resides into the System.Net.Http namespace. Jumping right into the code:
public async Task<string> GetPhotosStream(){
HttpClient client = new HttpClient();
string url = "http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&nojsoncallback=1&api_key=<yourkey>&text=buildwindows";
HttpResponseMessage response = await client.GetAsync(url);
return response.Content.ReadAsString();
}
GetAsync() will return a HttpResponseMessage, which contains the returned status code, response headers and returned content, which can be read in a variety of ways.
Parsing the JSON. I prefer to use JSON.net. A returned string can be fed to the JsonObject in its constructor or using Parse() method on its instance. Either way will result in an exception if the JSON string is invalid and couldn’t be parsed.
And this is how you would read the titles of returned photos:
private static List<string> titles = new List<string>();
public static async void ExaminePhotos(){
string responseText = await GetPhotosStream();
JsonObject root = new JsonObject(responseText);
bool isSuccess = root.GetNamedString("stat") == "ok";
JsonObject info = root.GetNamedObject("photos");
int page = (int)info.GetNamedNumber("page");
int totalPages = (int)info.GetNamedNumber("pages");
JsonArray photos = info.GetNamedArray("photo");
for (uint i = 0; i < photos.Count; i++) {
string title = photos.GetObjectAt(i).GetNamedString("title");
titles.Add(title);
}
}
While the “Named*" methods return typed values (GetNamedString() returns a string, GetNamedNumber() a double, etc.), it’s also possible to get the JSON value by string indexer and later call to its typed value, e.g. json[“stat”].GetString(), which gets useful if you want to check for its type first.
The second part deals with a JsonArray named photo, which gets enumerated and read in a similar manner
Of course, the DataContractJsonSerializer is still here. In fact, it appears to be the same class, just moved into a separate assembly.
string responseText = await GetPhotosStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RootObject));
RootObject root;
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(responseText))){
root = serializer.ReadObject(stream) as RootObject;
}
The result is a full object tree that was deserialized from the flickr API JSON string.