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

问题描述 投票:0回答:1
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 |字节位置内联:1.

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

c# .net restsharp
1个回答
0
投票

问题是您试图仅反序列化您获得的 JSON 的part。如果你仔细观察,传入的 JSON 有四个属性,

products
,这是你想要的产品数组,最后还有三个整数属性。

您可以通过添加额外的课程来做您想做的事...

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

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

希望一切都有意义。

© www.soinside.com 2019 - 2024. All rights reserved.