我在JSON序列化方面遇到一些问题。 当我尝试反序列化JSON对象时,它会向我返回此错误:
Newtonsoft.Json.JsonSerializationException:无法将当前JSON数组(例如[1,2,3])反序列化为类型'Project.Models.BookModel',因为该类型需要JSON对象(例如{“ name”:“ value “})正确反序列化。
我的问题是我必须以两种不同的方式反序列化对象:在JSON数组(例如[1,2,3])中提取“ _id”,“用户”和“名称”,然后在JSON数组(例如[“ name”:“ value”])以提取“ books”。而且我不知道该怎么做。更确切地说,我不知道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);
答案 0 :(得分:0)
在代码中的任何地方实现这些类,并尝试使用这些类反序列化json。
public class Author
{
public string _id { get; set; }
public string name { get; set; }
public int __v { get; set; }
}
public class Content
{
public string brief { get; set; }
}
public class Book
{
public string _id { get; set; }
public string title { get; set; }
public Author author { get; set; }
public string literaryGenre { get; set; }
public object isbn { get; set; }
public string externalImage { get; set; }
public int __v { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int __v { get; set; }
public string user { get; set; }
public string name { get; set; }
public List<Book> books { get; set; }
}
答案 1 :(得分:0)
无法将当前JSON数组(例如[1,2,3])反序列化为type 'Project.Models.BookModel',因为类型需要JSON对象 (例如{“ name”:“ value”})
在json
结果中,您的BookModel
返回多个记录,因此应将其定义为List<BookModel>
。
在LibraryModel
中尝试使用公共List<BookModel> books { get; set; }
。