c# - 在 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);
}
}
}
}
解决方案
如果您的 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();
推荐阅读
- perl - 带有 Mojo::UserAgent 非阻塞请求的“使用未初始化值 $_”警告
- python - 如何使用一行代码查看所有分类列及其信息?
- python-3.x - Matplotlib 绘图比例
- java - 如何从java中删除输入缓冲区
- javascript - javascript设置本地存储的奇怪问题
- ruby-on-rails - Rails - Safari 通过启用 AJAX 的链接发出额外请求
- python - 如何用 Python 添加 xml 标签?
- firebase - 在 Cloud Function 中触发 Firestore onDelete 后如何删除存储在 Firebase 存储中的图像?
- r - Boxplot 集成三个信息级别
- asp.net - 如何禁用重定向到 ASP NET 应用程序的登录页面