我想反序列化类似于以下内容的 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 也是如此(以逗号分隔的索引列表)