Home > Enterprise >  RestSharp jsonException: error. How do I deserialize?
RestSharp jsonException: error. How do I deserialize?

Time:01-15

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;
    }

ProductsController:

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

JsonException: The JSON value could not be converted to System.Collections.Generic.List`1[DummyShop.Service.ViewModel.ProductViewModel]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

I get this error. No matter what I did, I couldn't get over this problem. Likewise, the data I will need to send a post request belongs to DummyJson.

CodePudding user response:

The problem is that you are trying to deserialise only part of the JSON that you get. If you look carefully, the incoming JSON has four properties, products which is the array of products you want, as well as three integer propeties at the end.

You can do what you want by adding an extra class...

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

...and then your deserialisation will work fine.

I copied the JSON from the URL you included, and successfully deserialised it as follows...

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

This gave the all the data in the JSON. To access the products, you just look at data.Products.

Note that I added the case insensitivity part as your properties are all lower-case, and by default (depending on the environment you are deserialising in), the deserialiser expects capitalised property names.

Hope that all makes sense.

  • Related