Search code examples
c#wpfjsondatacontractserializer

WPF and Json Deserializer with multiple items


I'm trying to deserialize a give json string that has multiple device names and Ip addresses. The code that I am trying to work out is below.

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

When I do this I get a null value for the ControllerCollection. Any help is welcome. Thanks!


Solution

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

    Your Json string is in incorrect format.