首页 > 解决方案 > 在 C# 中反序列化 JSON 以进行数组和迭代

问题描述

我需要帮助才能知道我做错了什么,我很少有时间使用 c#。我无法迭代 json ,我正在使用 RestSharp 和 Newtonsoft.Json 。消息说::

"'无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'ConsoleApp1.Libro',因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。修复此错误要么将 JSON 更改为 JSON 对象(例如 {"name":"value"}),要么将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以反序列化的 List来自 JSON 数组。”

如果我打印 response.Content 它会返回正确的 json,但我无法使用 foreach 对其进行迭代

namespace ConsoleApp1
{
    public class Libro
    {
        public int id { get; set; }
        public string id_categoria { get; set; }
        public string tipo { get; set; }
        public string ruta { get; set; }
        public string autor { get; set; }
        public int estado { get; set; }
        public string titulo { get; set; }
        public string titular { get; set; }
        public int size { get; set; }
        public string detalles { get; set; }
        public double precio { get; set; }
        public string portada { get; set; }
        public int ventas { get; set; }
        public int oferta { get; set; }
        public double precioOferta { get; set; }
        public int entrega { get; set; }
        public string fecha { get; set; }
    }

    public class Cate
    {
        public int id { get; set; }
        public string categoria { get; set; }
        public string ruta { get; set; }
        public int estado { get; set; }
        public int oferta { get; set; }
        public int precioOferta { get; set; }
        public int descuentoOferta { get; set; }
        public string imgOferta { get; set; }
        public string finOferta { get; set; }
        public string fecha { get; set; }
        public IList<Libro> libros { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("mostrar registros");
            var client = new RestClient("myurl");
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            IRestResponse response = client.Execute(request);
            var resultado = new Libro();
            resultado = JsonConvert.DeserializeObject<Libro>(response.Content); /*(here is the error)*/

            foreach (var item in resultado.titulo)
            {
                Console.WriteLine(item);
            }

        }
    }
}

标签: c#jsonjson.netrestsharpjson-deserialization

解决方案


如果您的 response.Content 中有方括号,则可能会导致问题。如果是这种情况,请尝试:

resultado  = JSON.Deserialize<Libro>(response.Content.Substring(1, response.Content.Length-2));

或者您也可以在列表中反序列化并使用零索引来获取第一个。就像是:

var resultadoList   = JSON.Deserialize<List<Libro>>(response.Content);
resultado = resultadoList[0];

或者

var resultadoList   = JSON.Deserialize<List<Libro>>(response.Content);
resultado = resultadoList.FirstOrDefault();

推荐阅读