0

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

4

1 回答 1

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

于 2013-05-21T01:58:08.677 回答