简体   繁体   中英

One or more errors occurred. (Cannot deserialize the current JSON object (e.g))

Trying to deserialize an array of book objects from the GoogleBook API.

Models: https://pastebin.com/24S16hZc

Confirmed API respons: https://pastebin.com/2q0aFGnf

Booking Page:

  public BookingPage()
    {
        this.InitializeComponent();
        ResizeWindow();
        UpdateListView();

    }

    private void UpdateListView()
    {
        UserList_List.Items.Clear();

        foreach (HelperLibrary.UserObject L in App.GlobalUserList)
        {
            UserList_List.Items.Add($" { L.FirstName } { L.LastName }");

        }

        //Prepare task
        Task<HelperLibrary.Models.GoogleBook.RootObject[] > GetBooksTask = HelperLibrary.Helpers.APIHelper.SearchBooks("Hacker");

        GetBooksTask.Wait();

        HelperLibrary.Models.GoogleBook.RootObject[] Books = GetBooksTask.Result;

        foreach(HelperLibrary.Models.GoogleBook.RootObject P in Books)
        {
            BookList_list.Items.Add(P.volumeInfo.title);
        }


    }

API Helper task

 public class APIHelper
{
    private static string BaseURL = "https://www.googleapis.com/books/v1/volumes";

    public static async Task<HelperLibrary.Models.GoogleBook.RootObject[] > SearchBooks(string term)
    {

        using (var WebClient = new HttpClient { BaseAddress = new Uri(BaseURL) })
        {

            var ResponseHandler = WebClient.GetAsync($"?q= { term } ");


            if (ResponseHandler.Result.IsSuccessStatusCode)
            {
                string x = await ResponseHandler.Result.Content.ReadAsStringAsync();
                Debug.WriteLine(x);
                Models.GoogleBook.RootObject[] items = JsonConvert.DeserializeObject<Models.GoogleBook.RootObject[]>(await ResponseHandler.Result.Content.ReadAsStringAsync());
                return items;
            }
            else
            {
                return null;
            }


        }
    }




}

Full error:

JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[HelperLibrary.Models.GoogleBook+RootObject]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'kind', line 2, position 8.

I'm already trying to declare it to an array, not a List? Been trough most other threads about this, can't seem to find a situation similar to mine.

You seem to have misunderstood what is the RootObject . What you have defined as such is actually the inner object inside your RootObject .

I suggest you do this;

1) Rename your RootObject to Item

    public class Item
    {
        public string kind { get; set; }
        public string id { get; set; }
        public string etag { get; set; }
        public string selfLink { get; set; }
        public VolumeInfo volumeInfo { get; set; }
        public LayerInfo layerInfo { get; set; }
        public SaleInfo saleInfo { get; set; }
        public AccessInfo accessInfo { get; set; }
    }

2) Create a new RootObject

public class RootObject
{
    public string kind { get; set; }
    public int totalItems { get; set; }
    public List<Item> items { get; set; }
}

Then your Deserialize should look like this;

Models.GoogleBook.RootObject root = 
JsonConvert.DeserializeObject<Models.GoogleBook.RootObject>(await ResponseHandler.Result.Content.ReadAsStringAsync());

Checking the structure of the json, i think what you are trying to get is the item array of the json if i am not mistaken. What you can do is Try to create a parent class containing the array Root Object something like this:

Public class RootParent
{
    public string kind {get; set;}
    public int totalItems {get;set;}
    public List<RootObject> items {get; set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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