JsonSerializationException无法反序列化当前Json对象[重复]

0x6upsns  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(128)

此问题在此处已有答案

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly(6个答案)
昨天关门了。
我想从Gutenberg项目的Web API服务中获取数据,并以MVC结构创建一个站点。但在提取数据时遇到错误。我需要帮助。Web API:https://gutendex.com/
`

public async Task<IActionResult> GetBooksFromApi()
        {
            var books = new List<BookModel>();

            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("https://gutendex.com/books"))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    books = JsonConvert.DeserializeObject<List<BookModel>>(apiResponse);
                }
            }
            return View(books);
        }

`

public class BookModel
    {
        public int id { get; set; }
        public string Title { get; set; }
        public string[] Subjects { get; set; }
        public string[] Authors { get; set; }
        public string[] Translators { get; set; }
        public string[] Bookshelves { get; set; }
        public string[] Languages { get; set; }
        public bool Copyright { get; set; }
        public string Media_Type { get; set; }
        public string Formats { get; set; }
        public int Download_Count { get; set; }
    }
}

``
screenshot of the error
我想使用我的网站上使用Newtonsoft包收到的json数据,但是我在转换时遇到错误。

2vuwiymt

2vuwiymt1#

如果你只需要一个书的集合,你可以使用Parse提取它,然后反序列化为一个列表。

List<BookModel> results =JObject.Parse(json)["results"].ToObject<List<BookModel>>();

public class BookModel
{
    public int id { get; set; }
    public string Title { get; set; }
    public string[] Subjects { get; set; }
    public object[] Authors { get; set; }
    public string[] Translators { get; set; }
    public string[] Bookshelves { get; set; }
    public string[] Languages { get; set; }
    public bool Copyright { get; set; }
    public string Media_Type { get; set; }
    public object Formats { get; set; }
    public int Download_Count { get; set; }
}

我建议为Authors和Formats属性创建自定义类而不是对象

相关问题