Deserialize JSON in Silverlight 4

I have a MyItems class in my namespace as

[DataContract] public class MyItems { [DataMember] public int LineNum { get; set; } [DataMember] public string ItemCode { get; set; } [DataMember] public string Priority { get; set; } [DataMember] public string Contact { get; set; } [DataMember] public string Message { get; set; } } 

and on XAML I have a button and in its action performer, I try to deserialize the JSON string that comes from the form and tries to update the DataGrid.

In the first step, inside the action listener, I try ...

 List<MyItems> myItems= JSONHelper.DeserializeToMyItems<myItems>(result); 

and the result (type strings) has

 {"MyItems":[{"LineNum":"1","ItemCode":"A00001","Contact":"5","Priority":"1","Message":"IBM Infoprint 1312"}, {"LineNum":"2","ItemCode":"A00002","Contact":"5","Priority":"1","Message":"IBM Infoprint 1222"}, {"LineNum":"3","ItemCode":"A00003","Contact":"5","Priority":"1","Message":"IBM Infoprint 1226"}, {"LineNum":"4","ItemCode":"A00004","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 5"}, {"LineNum":"5","ItemCode":"A00005","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 4"}]} 

The JSONHelper.DeserializeToMyItems code is as follows:

 public static List<MyItems> DeserializeToMyItems<MyItems>(string jsonString) { MyItems data = Activator.CreateInstance<MyItems>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MyItems>)); return (List<MyItems>)serializer.ReadObject(ms); } } 

While working, I get an exception in the string serializer. ReadObject (ms)

 Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.List`1[ServiceTicket.MyItems]'. 

I am not sure how to make cast type for, and I am processing a list of MyItems types. Can someone help me with this please? would be highly appreciated since I'm new to Silverlight.

thanks

Danny

+4
source share
1 answer

Try to follow, it should solve your problem.

 public class JsonHelper { public static T Deserialize<T>(string json) { using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } } 

and use the method described above, for example:

 List<MyItems> myItems = JsonHelper.Deserialize<List<MyItems>>(result); 

Hope this helps!

+3
source

All Articles