gpt4 book ai didi

c# - 如何将具有索引引用的 JSON 数据反序列化为强类型 C# 对象?

转载 作者:行者123 更新时间:2023-11-30 17:57:59 25 4
gpt4 key购买 nike

我想反序列化 JSON 数据(使用 Newtonsoft),类似于以下内容,并在 C# 中转换为强类型对象/列表,但无法弄清楚如何定义类,以便将索引引用转换为引用对象。

{
"Countries": [
{
"Name": "USA",

},
{
"Name": "UK",
},
{
"Name": "JAPAN",
},
],
"Authors": [
{
"DisplayName": "John Doe",
"RealName": "Not John Doe"
},
{
"DisplayName": "Jane Doe",
"RealName": "Not Jane Doe"
},
],
"Books": [
{
"Author": 0,
"Title": "A good read",
"PublishedCountries": "0,1",

},
{
"Author": 0,
"Title": "Another good read",
"PublishedCountries": "0,1",
},
{
"Author": 1,
"Title": "This one is even better",
"PublishedCountries": "0,1,2",
},
],
}

理想情况下,我想使用类似于以下的类:

public class Country
{
public string Name { get; set;}
}

public class AuthorDetails
{
public string DisplayName { get; set; }
public string RealName { get; set; }
}

public class Book
{
public AuthorDetails Author { get; set; }
public string Title { get; set; }
public IEnumerable<Country> PublishedCountries { get; set; }
}

public class ListOfBooks
{
public IEnumerable<Book> Books { get; set; }
}

像这样反序列化:

var listOfBooks = JsonConvert.DeserializeObject<ListOfBooks>(jsonAsString);

我不知道如何告诉 Json.Net JObject 书中的 Author 属性是一个索引,而不是一个整数。 PublishedCountries 也是如此(这是以逗号分隔的索引列表)

最佳答案

除了稍微帮助反序列化过程之外,我看不到其他方法。

var dynObj = (JObject)JsonConvert.DeserializeObject(json);

var authors = dynObj["Authors"]
.Select(j => new AuthorDetails {
RealName = (string)j["RealName"],
DisplayName = (string)j["DisplayName"]
})
.ToList();

var countries = dynObj["Countries"]
.Select(j => new Country { Name = (string)j["Name"]})
.ToList();

var books = dynObj["Books"].Select(x => new Book
{
Author = authors[(int)x["Author"]],
Title = (string)x["Title"],
PublishedCountries = x["PublishedCountries"].ToString().Split(',')
.Select(i =>countries[int.Parse(i)])
.ToList()
})
.ToList();

public class Country
{
public string Name { get; set; }
}

public class AuthorDetails
{
public string DisplayName { get; set; }
public string RealName { get; set; }
}

public class Book
{
public AuthorDetails Author { get; set; }
public string Title { get; set; }
public List<Country> PublishedCountries { get; set; }
}

关于c# - 如何将具有索引引用的 JSON 数据反序列化为强类型 C# 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com