开发者

Deserialize JSON in Silverlight 4

开发者 https://www.devze.com 2023-01-19 07:44 出处:网络
I have a class MyItems in my namespace as [DataContract] public class MyItems{ [DataMember] public int LineNum { get; set; }

I have a class MyItems 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 an XAML I have a button and in its action listener, I am trying to deserialize the JSON string that is coming from a form and trying to update a DataGrid.

In the first step Inside the action listener, I am trying..

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

and result (of type string ) 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","ItemCo开发者_开发技巧de":"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 looks like,

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 running, I get an exception at the line 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 do a type cast for and I am handling a List of type MyItems. Can anyone help me on this please ?. would be highly appreciated as I am new on Silverlight.

thanks

Denny


Try following, it should resolve 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 above method like following:

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

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消