Deserialization of array with DataContractJsonSerializer with Windows Store App

佐手、 提交于 2019-12-12 04:38:09

问题


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:


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


来源:https://stackoverflow.com/questions/16772684/deserialization-of-array-with-datacontractjsonserializer-with-windows-store-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!