在Silverlight 4中反序列化JSON

时间:2010-10-11 15:20:36

标签: json silverlight-4.0

我的命名空间中有一个MyItems类

[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; }    
}

在XAML上我有一个按钮,在其动作监听器中,我试图反序列化来自表单的JSON字符串并尝试更新DataGrid。

在动作监听器内部的第一步中,我正在尝试..

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

和结果(字符串类型)

{"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"}]}

JSONHelper.DeserializeToMyItems代码如下所示,

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);            }        }

运行时,我在行serializer.ReadObject(ms)

处得到一个异常
Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.List`1[ServiceTicket.MyItems]'.

我不知道如何进行类型转换,我正在处理MyItems类型的List。请问有人帮我吗?因为我是Silverlight的新手,我将非常感激。

感谢

丹尼

1 个答案:

答案 0 :(得分:3)

请尝试以下操作,它应该可以解决您的问题。

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);
        }
    }
}

并使用以下方法:

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

希望这有帮助!