繁体   English   中英

RestSharp jsonException:错误。 我如何反序列化?

[英]RestSharp jsonException: error. How do I deserialize?

public class ProductViewModel
{
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public int price { get; set; }
    public double discountPercentage { get; set; }
    public double rating { get; set; }
    public int stock { get; set; }
    public string brand { get; set; }
    public string category { get; set; }
    public string thumbnail { get; set; }
    public List<string> images { get; set; }
}

}

--

 public class ProductClient : IProductClient
    {
        private readonly RestClient _client;
        private readonly string _url;

        public ProductClient()
        {
            _url = "https://dummyjson.com/products";
            var options = new RestClientOptions(_url);
            _client = new RestClient(options);
        }


   Task<List<ProductViewModel>> GetAllProduct();


 public async Task<List<ProductViewModel>> GetAllProduct()
    {
        var request = new RestRequest();
        //request.AddHeader("Accept", "application/json");

        var response = await _client.GetAsync<List<ProductViewModel>>(request);
        
        return response;
    }

产品控制器:

 [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var response = await _client.GetAllProduct();
            return Ok(response);
        }

JsonException: JSON 值无法转换为 System.Collections.Generic.List`1[DummyShop.Service.ViewModel.ProductViewModel]。 路径:$ | 行号:0 | BytePositionInLine:1。

我收到这个错误。 无论我做什么,我都无法克服这个问题。 同样,发送 post 请求所需的数据属于 DummyJson。

问题是您试图仅反序列化您获得的 JSON 的一部分 仔细看,传入的JSON有四个属性products就是你要的产品数组,最后还有三个integer属性。

你可以通过添加额外的 class 来做你想做的事......

oublic class Data {
  public ProductViewModel[] Products { get; set; }
  public int Total { get; set; }
  public int Skip { get; set; }
  public int Limit { get; set; }
}

...然后你的反序列化就可以正常工作了。

我从你包含的 URL 复制了 JSON,并成功反序列化如下......

Data data = JsonSerializer.Deserialize<Data>(json, 
     new JsonSerializerOptions {PropertyNameCaseInsensitive=true});

这给出了 JSON 中的所有数据。要访问产品,您只需查看data.Products

请注意,我添加了不区分大小写的部分,因为您的属性都是小写的,并且默认情况下(取决于您反序列化的环境),反序列化器需要大写的属性名称。

希望一切都有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM