简体   繁体   English

Json 反序列化创建空对象

[英]Deserialization of Json creates null object

The json can be found here: https://www.googleapis.com/books/v1/volumes?q=harry+potter json 可以在这里找到: https : //www.googleapis.com/books/v1/volumes? q=harry+potter

I'm having issues with deserializing the json into a list of book objects.我在将 json 反序列化为书籍对象列表时遇到问题。 I`m using two models, BookList and Books.我正在使用两种模型,BookList 和 Books。 Book list has a property called bookList which is just a list of Books. Book list 有一个名为 bookList 的属性,它只是一个 Books 列表。

When the code is run a Book List object is created, but its null.当代码运行时,会创建一个 Book List 对象,但它为 null。

Heres the code:代码如下:

BookList.cs书单.cs

using System.Collections.Generic;
using Newtonsoft.Json;

namespace HarryPotterBooksApp.Models
{
    public class BookList
    {
        [JsonProperty("items")]
        public List<Book> bookList {get;set;}
    }
}

Book.cs书.cs

using Newtonsoft.Json;

namespace HarryPotterBooksApp.Models
{
    public class Book
    {
      
        [JsonProperty("id")]
        public string id { get; set; }
        [JsonProperty("publisher")]
        public string publisher { get; set; }

    }
}

BookController.cs图书控制器.cs

namespace HarryPotterBooksApp.Controllers {
        public class BooksController: Controller {
            const string BASE_URL = "https://www.googleapis.com/books/v1/volumes?q=harry+potter";

            private readonly ILogger<BooksController> _logger;

            private readonly IHttpClientFactory _clientFactory;

            public BookList Books { get; set; }

            public bool GetBooksError { get; private set; }

            public BooksController (ILogger<BooksController> logger, IHttpClientFactory clientFactory)

            {

                _logger = logger;

                _clientFactory = clientFactory;

            }

            public async Task<IActionResult> Index ()

            {

                var message = new HttpRequestMessage ();

                message.Method = HttpMethod.Get;

                message.RequestUri = new Uri ($"{BASE_URL}api/Books");

                message.Headers.Add ("Accept", "application/json");

                var client = _clientFactory.CreateClient ();

                var response = await client.SendAsync (message);

                if (response.IsSuccessStatusCode) {

                    var responseString = await response.Content.ReadAsStringAsync();

                    Books = JsonConvert.DeserializeObject<BookList>(responseString);

                } else {

                    GetBooksError = true;

                    Books = new BookList();

                }

                return View (Books);

            }

Did you see the new library of Microsoft to deserialize JSON?看到微软反序列化JSON的新库了吗? It's called System.Text.Json, and it's amazing: https://docs.microsoft.com/fr-fr/dotnet/api/system.text.json?view=netcore-3.1它叫做 System.Text.Json,很神奇: https ://docs.microsoft.com/fr-fr/dotnet/api/system.text.json?view=netcore-3.1

Also you have Json.NET by Newtonsoft: https://www.newtonsoft.com/json你也有Json.NET通过Newtonsoft: https://www.newtonsoft.com/json

Your JSON seem pretty complicate, a solution is to write each object and deserialze the JSON with each object (but it will be too long).你的 JSON 看起来很复杂,一个解决方案是编写每个对象并用每个对象反序列化 JSON(但它会太长)。 Another solution is to build the representation by getting all the property.另一种解决方案是通过获取所有属性来构建表示。

You model doesn't match the source JSON, so that is going to be the first issue.您的模型与源 JSON 不匹配,因此这将是第一个问题。 The JSON has a single root object -- the root is not a list. JSON 有一个根对象——根不是一个列表。 That root contains kind, totalItems and items.该根包含 kind、totalItems 和 items。 The list of books is "items".书籍列表是“项目”。 You need a model that matches this.您需要一个与此匹配的模型。 Likewise, the id is in the item (your Book) object, but the publisher is in a child object (volumeInfo).同样,id 位于项目(您的 Book)对象中,但发布者位于子对象 (volumeInfo) 中。 If you model doesn't match, then your call to DeserializeObject isn't going to work.如果您的模型不匹配,那么您对 ​​DeserializeObject 的调用将不起作用。

Given the complexity of the JSON being returned, perhaps the easiest way to ensure your model matches this JSON is to generate a model using a tool, such as https://json2csharp.com/ or https://app.quicktype.io/?l=csharp , that will build the C# model from example JSON.鉴于返回的 JSON 的复杂性,确保您的模型与此 JSON 匹配的最简单方法可能是使用工具生成模型,例如https://json2csharp.com/https://app.quicktype.io/ ?l=csharp ,这将从示例 JSON 构建 C# 模型。 This will make sure your model matches the JSON and will provide a good starting point.这将确保您的模型与 JSON 匹配并提供一个良好的起点。 You can always remove properties and children if you don't need them.如果您不需要属性和子项,您可以随时删除它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM