gpt4 book ai didi

json - 在 Silverlight 4 中反序列化 JSON

转载 作者:行者123 更新时间:2023-12-01 02:53:38 27 4
gpt4 key购买 nike

我的命名空间中有一个类 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 上,我有一个按钮,在它的 Action 监听器中,我尝试反序列化来自表单的 JSON 字符串并尝试更新 DataGrid。

在第一步在 Action 监听器中,我正在尝试..
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 类型的列表。任何人都可以帮助我吗?将不胜感激,因为我是 Silverlight 的新手。

谢谢

丹尼

最佳答案

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

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

希望这可以帮助!

关于json - 在 Silverlight 4 中反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3907560/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com