我正在尝试将JSON字符串读入对象。我的数据与已回答的数据略有不同。
数据:
{
"rows": [
{
"id": 1,
"data": [
"First Column",
"Second Column",
"Third Column",
"Fourth Column",
"Fifth Column",
"Sixth Column"
]
},
{
"id": 2,
"data": [
"First Column",
"Second Column",
"Third Column",
"Fourth Column",
"Fifth Column",
"Sixth Column"
]
},
{
"id": 3,
"data": [
"First Column",
"Second Column",
"Third Column",
"Fourth Column",
"Fifth Column",
"Sixth Column"
]
}
]
}
我尝试了以下方法:
dynamic results = JsonConvert.DeserializeObject<dynamic>(jsonData);
var o = JsonConvert.DeserializeObject(jsonData, typeof(List<CommonPage>), new JsonSerializerSettings());
CommonPage是我的类,它有一组属性,例如:
1. First Column
2. Second Column
我想反序列化为对象列表,以便我可以编辑反序列化的数据。 似乎没有直接的答案。
我在想也许我可以从 JSON 数据中获取类似List<CommonPage>
的东西,以便我能够访问如下数据:
List<CommonPage>[0].FirstColumn
(这只是一个示例:这是可以使用数据中的id
LINQ 查询的第一行数据。
您必须向新类提供一个名为 Rows 的属性,然后实例化为 List。
您将使用此新类作为反序列化的类型
您可以使用 quicktype 生成 json 类:https://app.quicktype.io?share=9B7eToMMux9sDZaYkQgs
示例:https://dotnetfiddle.net/0SjzkT
创建模型类:
public partial class Pages
{
public List<Page> Rows { get; set; }
public override string ToString()
{
return string.Join("rn", this.Rows.Select(q=>q.ToString()).ToArray());
}
}
public partial class Page
{
public long Id { get; set; }
public List<string> Data { get; set; }
public override string ToString()
{
return "ID: " + this.Id.ToString() + " - Data: " + string.Join(", ", this.Data.Select(q=>q.ToString()).ToArray());
}
}
获取不同的值:
public static void Main()
{
string jsonStr = @"{'rows': [ ...";
var ret = JsonConvert.DeserializeObject<Pages>(jsonStr) as Pages;
Console.WriteLine(string.Join("rn", ret.Rows.SelectMany(q=>q.Data).Distinct().ToArray()));
}
获取所有值:
public static void Main()
{
string jsonStr = @"{'rows': [ ...";
var ret = JsonConvert.DeserializeObject<Pages>(jsonStr) as Pages;
Console.WriteLine(ret.ToString());
}
输出:
First Column
Second Column
Third Column
Fourth Column
Fifth Column
Sixth Column
ID: 1 - Data: First Column, Second Column, Third Column, Fourth Column, Fifth Column, Sixth Column
ID: 2 - Data: First Column, Second Column, Third Column, Fourth Column, Fifth Column, Sixth Column
ID: 3 - Data: First Column, Second Column, Third Column, Fourth Column, Fifth Column, Sixth Column
最简单的方法可能是反序列化为 JObject 并执行手动转换:
var o = JsonConvert.DeserializeObject<JObject>(json)["rows"].Select(r => new CommonPage
{
FirstColumn = r["data"][0].Value<string>(),
SecondColumn = r["data"][1].Value<string>(),
// etc.
})
.ToList();