问题
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