Home > Blockchain >  C# Json.net Unexpected character encountered while parsing value:
C# Json.net Unexpected character encountered while parsing value:

Time:04-14

I am getting the above error while trying to get the Json format from a url.

  public class Product
{
    public int Id { get; set; }
    [JsonProperty("externalId")]
    public int ExternalId { get; set; }
    [JsonProperty("code")]
    public string Code { get; set; }
    [JsonProperty("description")]
    public string Description { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("barcode")]
    public int Barcode { get; set; }
    [JsonProperty("retailPrice")]
    public double RetailPrice { get; set; }
    [JsonProperty("wholesalePrice")]
    public double WholesalePrice { get; set; }
    [JsonProperty("discount")]
    public double Discount { get; set; }
}

public class Products
{
    public List<Product> GetProducts { get; set; }
}

and in my controller I have:

        public async Task<ActionResult> Index()
    {
        string url = "https://cloudonapi.oncloud.gr/s1services/JS/updateItems/cloudOnTest";
        HttpClient client = new HttpClient();

        var httpResponseMessage = await client.GetAsync(url);
        httpResponseMessage.EnsureSuccessStatusCode();
        string jsonResponse = await httpResponseMessage.Content.ReadAsStringAsync();

        var list = JsonConvert.DeserializeObject<Products>(jsonResponse);

        return View(list);

    }

I keep getting the Unexpected character encountered while parsing value: . Path '', line 0, position 0. error

CodePudding user response:

So. \u001f means you received the byte 1F. is in the range of extended ASCII with encoding 8B. \b is the ASCII backspace character with encoding 08.

1F 8B is the magic number for GZIP (and the 08 is the compression method: DEFLATE).

So, the server's one of the broken ones which gives you back a gzip-compressed response, even though you didn't say you could accept gzip-compressed responses.

You can tell HttpClient to automatically decompress gzip-compressed responses:

HttpClientHandler handler = new HttpClientHandler()
{
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using var client = new HttpClient(handler));

var httpResponseMessage = await client.GetAsync(url);
// ...
  • Related