将 JSON 对象反序列化为 C# 列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16019729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserializing JSON object into a C# list
提问by user2282587
I'm trying to deserialize a given JSON file in C# using a tutorial by Bill Reiss. For XML data in a non-list this method works pretty well, though I would like to deserialize a JSON file with the following structure:
我正在尝试使用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; }
}
My problem is with using JSON.Net's ability to create / put data into lists, and then displaying the list on an XAML page. My idea so far (which is not working):
我的问题是使用 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;
采纳答案by cgotberg
So I think you're probably trying to deserialize to the wrong type. If you serialized it to RootObject and try to deserialize to List it's going to fail.
所以我认为您可能试图反序列化为错误的类型。如果您将其序列化为 RootObject 并尝试反序列化为 List,它将失败。
See this example code
请参阅此示例代码
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; }
}
Edit: Added complete code.
编辑:添加了完整的代码。

