首页 > 解决方案 > 无法反序列化当前的 json 对象

问题描述

我正在尝试调用一个包含基于查询字符串的图像列表的 api 端点。所以,如果我正在寻找猫的照片,我传递那个参数,api 键,我可以取回猫的照片。

我正在使用的 api 端点是: https ://pixabay.com/api/

这是该 api 的示例响应:

{
"total": 4692,
"totalHits": 500,
"hits": [
    {
        "id": 195893,
        "pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
        "type": "photo",
        "tags": "blossom, bloom, flower",
        "previewURL": "https://cdn.pixabay.com/photo/2013/10/15/09/12/flower-195893_150.jpg"
        "previewWidth": 150,
        "previewHeight": 84,
        "webformatURL": "https://pixabay.com/get/35bbf209e13e39d2_640.jpg",
        "webformatWidth": 640,
        "webformatHeight": 360,
        "largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
        "fullHDURL": "https://pixabay.com/get/ed6a9369fd0a76647_1920.jpg",
        "imageURL": "https://pixabay.com/get/ed6a9364a9fd0a76647.jpg",
        "imageWidth": 4000,
        "imageHeight": 2250,
        "imageSize": 4731420,
        "views": 7671,
        "downloads": 6439,
        "favorites": 1,
        "likes": 5,
        "comments": 2,
        "user_id": 48777,
        "user": "Josch13",
        "userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg",
    },
    {
        "id": 73424,
        ...
    },
    ...
]
}

这是我设置的 api 调用:

 public async Task<List<Image>> GetCatImages()
        {
            string query = "cats";
            return await Get<List<Image>>(_baseUrl + $"?key={apiKey}&q={query}&image_type=photo");
        }

这是get方法:

protected async Task<T> Get<T>(string url)
{
    using (HttpClient client = GetClient())
    {
        try
        {
            var response = await client.GetAsync(url);
                var obj = JsonConvert.DeserializeObject<T>(
                                await response.Content.ReadAsStringAsync());

                return obj;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}

我遇到的主要问题是:我认为 get 方法已损坏。我无法正确反序列化 JSON,而且我不确定我上面所做的是否错误。设置 obj(反序列化部分)后,我的代码中断。我究竟做错了什么?

以下是异常详细信息:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Models.Image]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) 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 'totalHits', line 1, position 13.

标签: c#jsonjson.netdotnet-httpclient

解决方案


您正在尝试将您的 Json 反序列化为 a List<Image>,但您的 Json 实际上只是一个Image对象(内部包含一个列表)。

将您的电话更改为以下电话:

await Get<Image>(yourUri)

推荐阅读