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

时间:2013-05-21 00:16:21

标签: c# wpf json datacontractserializer

我正在尝试反序列化具有多个设备名称和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的空值。 欢迎任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

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字符串格式不正确。