具有多个项目的WPF和Json反序列化器

本文关键字:Json 反序列化 WPF 项目 | 更新日期: 2023-09-27 18:14:24

我试图反序列化一个有多个设备名称和Ip地址的json字符串。我试图解决的代码如下:

var rawData = "[{'"Name'" : '"xbox'", '"IP'" : '"192.100.14.160'"} ,{'"Name'" : '"ps3'", '"IP'" : '"192.100.14.131'"}]";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(deviceCollection));
MemoryStream sr = new MemoryStream(Encoding.Unicode.GetBytes(rawData));
ControllerCollection pat = serializer.ReadObject(sr) as ControllerCollection;
sr.Close();
[DataContract]
public class ControllerCollection
{
    [DataMember]
    public List<Controller> Controllers { get; set; }
}
[DataContract]
public class Controller
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string IP { get; set; }
}

当我这样做时,我得到ControllerCollection的空值。欢迎任何帮助。谢谢!

具有多个项目的WPF和Json反序列化器

var rawData = "{'"Controllers'": [{'"Name'" : '"xbox'", '"IP'" : '"192.100.14.160'"} ,{'"Name'" : '"ps3'", '"IP'" : '"192.100.14.131'"}]}";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ControllerCollection), new Type[] {typeof(Controller)});
MemoryStream sr = new MemoryStream(Encoding.Unicode.GetBytes(rawData));
//sr.Seek(0, SeekOrigin.Begin);
ControllerCollection pat = (ControllerCollection)serializer.ReadObject(sr);
sr.Close();

Json字符串格式错误