Reputation: 5480
I have managed to set-up a simple webClient
that calls my WCF service in a WP8 application. The method fires perfectly fine and the data is returned via the OpenReadCompleted
event.
What I wish to do now is convert the returned data which is in JSON and populate a collection of objects.
This is the webClient
code:
private void Button_Click(object sender, RoutedEventArgs e)
{
var webClient = new WebClient();
var uri = new Uri("urlGoesHere");
webClient.OpenReadCompleted += webClient_OpenReadCompleted;
webClient.OpenReadAsync(uri);
}
This is the OpenReadComplete
code:
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var sr = new StreamReader(e.Result);
var data = sr.ReadToEnd();
//ToDo - Create a collection of SightingTypes and populate
sr.Close();
sr.Dispose();
}
And this is the POCO/Object which I want populating:
public class SightingType
{
public string Name { get; set; }
public string BrandId { get; set; }
}
UPDATE
When I hover over data, I can see the following (shortened):
{\"Message\":null,\"Status\":0,\"CurrentVersionNumber\":26,\"SightingTypes\":[{\"BrandId\":\"brands\\/1\",\"DestinationUserIds\":[\"users\\/33\"],\"Id\":\"SightingTypes\\/8\",\"IsDeleted\":false,\"IsEnabled\":true,\"Name\":\"Michael Johnson\"}
What I am particularly interested in is the Name and the BrandId.
Upvotes: 0
Views: 343
Reputation: 1578
I would recommend checking out JSON.Net. It comes with a JSON Serializer that should meet your need:
SightingType deserializedSightingType = JsonConvert.DeserializeObject<SightingType>(data);
Upvotes: 2
Reputation: 35363
You can use Json.Net and following classes (your root object is not SightingType )....
var result = JsonConvert.DeserializeObject<Response>(data);
public class SightingType
{
public string BrandId { get; set; }
public List<string> DestinationUserIds { get; set; }
public string Id { get; set; }
public bool IsDeleted { get; set; }
public bool IsEnabled { get; set; }
public string Name { get; set; }
}
public class Response
{
public object Message { get; set; }
public int Status { get; set; }
public int CurrentVersionNumber { get; set; }
public List<SightingType> SightingTypes { get; set; }
}
Also see this site where you can get the class definitions for your json string
Upvotes: 2
Reputation: 299
use this code to parse JSON into POCO
//get the JSON string into 'responseText'
// Deserialize response Message to JsonResponse
var serializer = new JavaScriptSerializer();
jsonResponse = serializer.Deserialize<JsonResponse>(responseText);
// where in <> put your class 'SightingType'
you will need to add resource System.Web.Extensions.dll in order to use JavaScriptSerializer class
Upvotes: 1