我正在尝试使用Bill Reiss的教程在c#中反序列化给定的JSON文件。对于非列表中的XML数据,此方法工作得非常好,不过我想用以下结构反序列化JSON文件:
public class Data
{
public string Att1 { get; set; }
public string Att2 { get; set; }
public string Att3 { get; set; }
public string Att4 { get; set; }
}
public class RootObject
{
public List<Data> Listname { get; set; }
}
我的问题是使用JSON。Net创建/将数据放入列表,然后在XAML页面上显示列表的能力。到目前为止,我的想法(这是行不通的):
var resp = await client.DoRequestJsonAsync<DATACLASS>("URL");
string t = resp.ToString();
var _result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DATACLASS>>(t);
XAMLELEMENT.ItemsSource = _result;
我想你可能反序列化到错误的类型。如果你将它序列化到RootObject,然后试图反序列化到List,它将会失败。
查看示例代码
public void TestMethod1()
{
var items = new List<Item>
{
new Item { Att1 = "ABC", Att2 = "123" },
new Item { Att1 = "EFG", Att2 = "456" },
new Item { Att1 = "HIJ", Att2 = "789" }
};
var root = new Root() { Items = items };
var itemsSerialized = JsonConvert.SerializeObject(items);
var rootSerialized = JsonConvert.SerializeObject(root);
//This works
var deserializedItemsFromItems = JsonConvert.DeserializeObject<List<Item>>(itemsSerialized);
//This works
var deserializedRootFromRoot = JsonConvert.DeserializeObject<Root>(rootSerialized);
//This will fail. YOu serialized it as root and tried to deserialize as List<Item>
var deserializedItemsFromRoot = JsonConvert.DeserializeObject<List<Item>>(rootSerialized);
//This will fail also for the same reason
var deserializedRootFromItems = JsonConvert.DeserializeObject<Root>(itemsSerialized);
}
class Root
{
public IEnumerable<Item> Items { get; set; }
}
class Item
{
public string Att1 { get; set; }
public string Att2 { get; set; }
}
编辑:添加完整代码