我正在尝试使用tutorial by 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;
答案 0 :(得分:22)
所以我认为你可能试图反序列化为错误的类型。如果你将它序列化为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; }
}
编辑:添加完整代码。