C# Json.net 解析值时遇到意外字符:

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

我在尝试从 url 获取 Json 格式时遇到上述错误。

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

在我的控制器中我有:

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

    }

我不断收到 解析值时遇到的意外字符:。路径 '',第 0 行,位置 0。 错误

所以。 \u001f 表示您收到了字节 1Fextended ASCII 范围内,编码为 8B\b 是编码为 08.

的 ASCII 退格字符

1F 8Bmagic number for GZIP (and the 08 is the compression method:放气)。

因此,即使您没有说可以接受 gzip-compressed 响应,服务器也是其中之一,它会返回 gzip-compressed 响应。

你可以告诉HttpClient自动解压gzip-compressed回复:

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

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