Deserialization of array with DataContractJsonSeri

2019-09-07 02:21发布

Is it possible to deserialize a json array with native DataContractJsonSerializer in a Windows Store App?

Example, from:

[{"groups":[{"name":"tom","vip":false},{"name":"sam","vip":true}]},{"groups":[{"name":"pam","vip":false},{"name":"mom","vip":true}]}]

To, anything roughly in the line of:

public class Group
{
    public string name { get; set; }
    public bool vip { get; set; }
}

[DataContract]
public class RootObject
{
    [DataMember]
    public List<Group> groups { get; set; }
}

So far, my attempts always resulted in a 'null' List or 'null' IEnumerable when doing it this way:

    public static T deserializeJson<T>(string result)
    {
        DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result)))
        {
            ms.Position = 0;
            return (T)jsonSer.ReadObject(ms);
        }
    }

1条回答
Juvenile、少年°
2楼-- · 2019-09-07 03:09

All the things are correct. Just write these line to get the object array.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    string json = @"[{""groups"":[{""name"":""tom"",""vip"":false},{""name"":""sam"",""vip"":true}]},{""groups"":[{""name"":""pam"",""vip"":false},{""name"":""mom"",""vip"":true}]}]";
    var res = deserializeJson<RootObject[]>(json);
    //OR
    var res1 = deserializeJson<List<RootObject>>(json);
}
查看更多
登录 后发表回答