我对 JSON 序列化有一些问题。当我尝试反序列化我的 JSON 对象时,它返回了这个错误:
Newtonsoft.Json.JsonSerializationException:无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“Project.Models.BookModel”,因为该类型需要 JSON 对象(例如 {"name":"value"})正确反序列化。
我的问题是我必须以两种不同的方式反序列化我的对象:在 JSON 数组(例如 [1,2,3])中提取“_id”、“user”和“name”,然后在 JSON 数组中(eg["name":"value"]) 提取“书籍”。而且我不知道该怎么做。或者更准确地说,我不知道 Refit 是否可行。
这是我的 JSON:
[
{
"_id": "5c014a1e43b6804ed7b642b2",
"__v": 0,
"user": "5c014a1d43b6804ed7b642b1",
"name": "Favoris",
"books": [
{
"_id": "5a8f12e16a16fa06d1f5b0cb",
"title": "Harry Potter et la Chambre des Secrets",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101049,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test1"
}
},
{
"_id": "5a8f12e16a16fa06d1f5b0d0",
"title": "Harry Potter et la Coupe de Feu",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101063,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test2"
}
}
]
}
]
这是我的代码:
public async void ViewLibrary()
{
IProjectApi response = ProjectRepository.Instance.ProjectApi;
List<LibraryModel> library = await response.GetLibrary("5c014a1d43b6804ed7b642b1");
this.LibraryItems = library;
}
还有我的对象 LibraryModel :
public class LibraryModel
{
public string _id { get; set; }
public string user { get; set; }
public string name { get; set; }
public BookModel books { get; set; }
}
我的方法 GetLibrary :
[Get("/api/library/user/{UserId}")]
Task<List<LibraryModel>> GetLibrary(string UserId);