Hi There, I have a JSON output (from WCF service) that I need to bind to a data grid. The Json i am getting is the result of a query that is dynamic. Due to this reason, I am able to cast the Json into an object. I wanted to check if someone else has implemented this. Thanks Jay
Hi Jay,
The XamGrid requires some sort of IEnumerable of a known type in order to bind to it. This means you need to create a class type that will contain the data inside the JSON string and give the grid a collection of this class. For example, take the following JSON:
[{"Name":"John Doe", "Email":"johnd@hotmail.com"},{"Name":"Mary Doe", "Email":"maryd@hotmail.com"}]
This JSON has two objects containing a 'Name' and 'Email' field so we need a class to contain these properties.
public class Person { public string Name { get; set; } public string Email { get; set; } }
You then need to parse the JSON and store the values in the Person class and then stick it inside a collection.
List<Person> people = ParseJSON(jsonString); xamGrid1.ItemsSource = people;
Deserializing the JSON into a class can be done using the DataContractJsonSerializer. This article discusses this: http://www.silverlightshow.net/items/JSON-serialization-and-deserialization-in-Silverlight.aspx
Thanks for the feedback, the problem is that I dont have fixed output. if I had known that I am getting Person class then this apporach would work fine but in my case I dont have this knowledge. I might get a response that would have and ID and EMAIL but another result might return ID, LOCATION. Thanks Jay
I looked into how you could handle this situation where you don't know what the properties are in the objects and I came up with the following solution:
Since you're using Silverlight you should have access to the JsonValue class. You need to add a reference to the System.Json assembly in order to get it. Once you have this class, you can use the JsonValue.Parse method to parse the data into KeyValuePairs. From these pairs you would need to create a column for the XamGrid and assign the Key property. You can then directly set the JsonValue to the XamGrid.ItemsSource. You must make sure that you set XamGrid.AutoGenerateColumns to false for this to work. I've attached a sample that demonstrates this.
Let me know if you have any further questions on this matter.
Hi Rob,
I have another question for you, I get double quotes when adding the data in grid. What is teh best way to remove these double quotes. Please see the image attached. Appreciate your feedback.
Thanks
Jay