本文介绍了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);

这是结果字符串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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 11:45