JsonConvert.DeserializeObject< IEnumerable< Book> [英] JsonConvert.DeserializeObject<IEnumerable<Book>>

查看:117
本文介绍了JsonConvert.DeserializeObject< IEnumerable< Book>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在使用这些语句时出现此错误:

I want to know why I get this error when I use these statements:

string result = await client.GetStringAsync(RestUrl);

return JsonConvert.DeserializeObject<IEnumerable<Book>>(result);

无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1 [BookClient.Data.Book]',因为该类型需要JSON数组(例如[1,2,3])正确反序列化. 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型.数组或列表),可以从JSON对象反序列化.还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[BookClient.Data.Book]' 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) 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

这是结果字符串File:

this is the result string File:

"{\"TOTAL\":177,\"PRODUCTS\":[{\"CODE\":\"T55-2A\",\"PRICE\":59.9500,\"NAME\":\"Arrive In Style\"},{\"CODE\":\"F1-231\",\"PRICE\":49.9500}]}"

谢谢

推荐答案

您似乎正在尝试将对象反序列化为数组.您需要创建一个包含内部数组的类.像这样:

You seem to be trying to deserialize an object into an array. You need to create a class that contains an array inside. Something like this:

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            const string result = "{\"TOTAL\":177,\"PRODUCTS\":[{\"CODE\":\"T55-2A\",\"PRICE\":59.9500,\"NAME\":\"Arrive In Style\"},{\"CODE\":\"F1-231\",\"PRICE\":49.9500}]}";

            var deserialized = JsonConvert.DeserializeObject<Result>(result);

            Debug.Assert(deserialized.Books.Count == 2);
        }
    }

    public class Result
    {
        [JsonProperty("TOTAL")]
        public int Total { get; set; }

        [JsonProperty("PRODUCTS")]
        public List<Book> Books { get; set; }
    }

    public class Book
    {
        [JsonProperty("CODE")]
        public string Code { get; set; }

        [JsonProperty("PRICE")]
        public float Price { get; set; }

        [JsonProperty("NAME")]
        public string Name { get; set; }
    }
}

这篇关于JsonConvert.DeserializeObject&lt; IEnumerable&lt; Book&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆