Home > Software engineering >  Error Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing valu
Error Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing valu

Time:07-24

I have this problem, I believe it's something in Json, but I've tried everything and I'm not able to return the objects.

My code:

        public List<Product> List()
        {
            var retorno = new List<Product>();
            try
            {
                using (var client = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://teste.teste1.com.br/app/Api/V1/Products/list"))
                    {
                        client.DefaultRequestHeaders.Add("x-user-email", "[email protected]");
                        client.DefaultRequestHeaders.Add("x-api-key", "eyJ0edsasa3121dasdas312dsa");
                        client.DefaultRequestHeaders.Add("x-store-key", "1");
                        request.Content = new StringContent("Content-Type", Encoding.UTF8, "application/json");
                        client.DefaultRequestHeaders.Add("accept", "application/json;charset=UTF-8");
                        var response = client.SendAsync(request);
                        //var response = client.GetStringAsync(uprApi   "app/Api/V1/Products/list");
                        response.Wait();
                        retorno = JsonConvert.DeserializeObject<Product[]>(response.Result.ToString()).ToList();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return retorno;
        }

Image Error: Error

EDIT:

My json:

{
    "success": true,
    "offset": 0,
    "result": {
        "error": false,
        "registers_count": 5,
        "pages_count": 1,
        "page": 1,
        "data": [
            {
                "product": {
                    "sku": "01",
                    "name": "Produto teste 01",
                    "description": "Produto de teste 01.",
                    "status": "enabled",
                    "qty": 30,
                    "price": 149.9,
                    "list_price": 199.9,
                    "weight_gross": 0.1,
                    "weight_liquid": 0.1,
                    "height": 1,
                    "width": 1,
                    "length": 1,
                    "items_per_package": "1",
                    "brand": "Colcci",
                    "ean": null,
                    "ncm": null,
                    "categories": [
                        {
                            "code": "339",
                            "name": "ESPORTES/Academia e Fitness/Roupas"
                        }
                    ]
                }
            },
            {
                "product": {
                    "sku": "3",
                    "name": "Produto DESATIVADO",
                    "description": "xyz",
                    "status": "disabled",
                    "qty": 0,
                    "price": 5.8,
                    "list_price": null,
                    "weight_gross": 0.1,
                    "weight_liquid": 0.1,
                    "height": 1,
                    "width": 1,
                    "length": 1,
                    "items_per_package": "1",
                    "brand": "Colcci",
                    "ean": null,
                    "ncm": null,
                    "categories": [
                        {
                            "code": null,
                            "name": null
                        }
                    ],
                    "variation_attributes": [
                        "UN"
                    ]
                }
            },
            {
                "product": {
                    "sku": "2",
                    "name": "Produto X",
                    "description": "xyz",
                    "status": "enabled",
                    "qty": 0,
                    "price": 5.8,
                    "list_price": null,
                    "weight_gross": 0.1,
                    "weight_liquid": 0.1,
                    "height": 1,
                    "width": 1,
                    "length": 1,
                    "items_per_package": "1",
                    "brand": "Colcci",
                    "ean": null,
                    "ncm": null,
                    "categories": [
                        {
                            "code": null,
                            "name": null
                        }
                    ],
                    "variation_attributes": [
                        "UN"
                    ]
                }
            },
            {
                "product": {
                    "sku": "1",
                    "name": "Produto",
                    "description": "Descrição do Produto Criado",
                    "status": "disabled",
                    "qty": 176,
                    "price": 5.9,
                    "list_price": 5.8,
                    "weight_gross": 0.1,
                    "weight_liquid": 0.1,
                    "height": 1,
                    "width": 1,
                    "length": 1,
                    "items_per_package": "1",
                    "brand": "Colcci",
                    "ean": "7896044963486",
                    "ncm": null,
                    "categories": [
                        {
                            "code": "3",
                            "name": "FEMININO/Roupas/Blusas e Camisas"
                        }
                    ],
                    "variations": [
                        {
                            "sku": "P_B",
                            "qty": 12,
                            "EAN": null,
                            "price": 5.8,
                            "list_price": 5.8,
                            "images": [],
                            "variant": [
                                {
                                    "size": "p"
                                },
                                {
                                    "color": "Branco"
                                }
                            ]
                        },
                        {
                            "sku": "M_P",
                            "qty": 14,
                            "EAN": null,
                            "price": 5.8,
                            "list_price": 5.8,
                            "images": [],
                            "variant": [
                                {
                                    "size": "m"
                                },
                                {
                                    "color": "Preto"
                                }
                            ]
                        },
                        {
                            "sku": "ABC1",
                            "qty": 150,
                            "EAN": null,
                            "price": 5.9,
                            "list_price": 5.8,
                            "images": [],
                            "variant": [
                                {
                                    "size": "p"
                                },
                                {
                                    "color": "Azul"
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "product": {
                    "sku": "GG004",
                    "name": "Gabinete Gamer",
                    "description": "Gabinete Gamer com RGB",
                    "status": "enabled",
                    "qty": 6,
                    "price": 399.9,
                    "list_price": 399.9,
                    "weight_gross": 0.3,
                    "weight_liquid": 0.25,
                    "height": 9,
                    "width": 3,
                    "length": 5,
                    "items_per_package": "1",
                    "brand": "Colcci",
                    "ean": null,
                    "ncm": null,
                    "categories": [
                        {
                            "code": "276",
                            "name": "CELULARES & ELETRÔNICOS/Informática/Games"
                        }
                    ],
                    "images": [
                        "https://manairadigitalteste.conectala.com.br/app/assets/images/product_image/4B3451F8-C862-7884-D169-5F256FA31F91/16581443192118.jpg"
                    ],
                    "published_marketplace": {
                        "ManairaDigital": "5_ManairaDigital"
                    },
                    "marketplace_offer_links": [
                        {
                            "name": "ManairaDigital",
                            "href": "https://manairadigital.com.br/gabinete-gamer-29/p"
                        }
                    ]
                }
            }
        ]
    }
}

EDIT 2: HEADERS:

             {"x-user-email", "[email protected]"},
             {"x-api-key", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2Rfc3RvcmUiOjMsImNvZF9jb21wYW55Ijo3fQ.E_sxhnwcmN5GtNGRYbVD66ciMi3JoJNjormS1q3mxYg"},
             {"x-store-key", "3"},
             {"Content-Type", "application/json"},
             {"accept", "application/json;charset=UTF-8"}

teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste

EDIT 3 enter image description here

CodePudding user response:

First of all using Wait you have a synchronous code and will block the thread until the task completes. You should await the request so it will asynchronous wait the task to complete. Try this instead and mark async the method that wraps this request to get the json response asynchronously:

// You need to return an IEnumerable of products
public async Task<IEnumerable<Product>> ListAsync() 
{
     var client = new HttpClient
     {
         BaseAddress = new Uri("https://manairadigitalteste.conectala.com.br")
     };

    client.DefaultRequestHeaders.Add("x-user-email", "your-email");
    client.DefaultRequestHeaders.Add("x-api-key", "your-key");
    client.DefaultRequestHeaders.Add("x-store-key", "3");
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    using var req = new HttpRequestMessage(HttpMethod.Get, "/app/Api/V1/Products/list");
    req.Content = new StringContent("", Encoding.UTF8, "application/json");
    using var res = await client.SendAsync(req);    
    res.EnsureSuccessStatusCode();
    var responseBody= await res.Content.ReadAsStringAsync();
    var root = JsonSerializer.Deserialize<Rootobject>(responseBody);
    var output = new List<Product>();
    root?.result.data.ToList().ForEach(x => output.Add(x.product));
    return output;
}

Then paste json as classes from menu in visual studio Edit->Paste Special->Paste JSON as classes. If you do this will get these classes:

public class Rootobject
{
    public bool success { get; set; }
    public int offset { get; set; }
    public Result result { get; set; }
}

public class Result
{
    public bool error { get; set; }
    public int registers_count { get; set; }
    public int pages_count { get; set; }
    public int page { get; set; }
    public Datum[] data { get; set; }
}

public class Datum
{
    public Product product { get; set; }
}

public class Product
{
    public string sku { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string status { get; set; }
    public int qty { get; set; }
    public float price { get; set; }
    public float? list_price { get; set; }
    public float weight_gross { get; set; }
    public float weight_liquid { get; set; }
    public int height { get; set; }
    public int width { get; set; }
    public int length { get; set; }
    public string items_per_package { get; set; }
    public string brand { get; set; }
    public string ean { get; set; }
    public object ncm { get; set; }
    public Category[] categories { get; set; }
    public string[] variation_attributes { get; set; }
    public Variation[] variations { get; set; }
    public string[] images { get; set; }
    public Published_Marketplace published_marketplace { get; set; }
    public Marketplace_Offer_Links[] marketplace_offer_links { get; set; }
}

public class Published_Marketplace
{
    public string ManairaDigital { get; set; }
}

public class Category
{
    public string code { get; set; }
    public string name { get; set; }
}

public class Variation
{
    public string sku { get; set; }
    public int qty { get; set; }
    public object EAN { get; set; }
    public float price { get; set; }
    public float list_price { get; set; }
    public object[] images { get; set; }
    public Variant[] variant { get; set; }
}

public class Variant
{
    public string size { get; set; }
    public string color { get; set; }
}

public class Marketplace_Offer_Links
{
    public string name { get; set; }
    public string href { get; set; }
}

Last in your controller do this:

 // GET: ProdutosController
public async Task<ActionResult> Index()
{
    var products = await _IProduto.ListAsync();
    return View(products);
}

A note about HttpClient:

HttpClient is intended to be instantiated once and reused throughout the life of an application. In .NET Core and .NET 5 , HttpClient pools connections inside the handler instance and reuses a connection across multiple requests. If you instantiate an HttpClient class for every request, the number of sockets available under heavy loads will be exhausted. This exhaustion will result in SocketException errors.

For a better design read this: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0

CodePudding user response:

Yes, You are right. I had same problem when deserialize the class. The problem is on you json when deserialize the object.Use this class when deserialize.

public class Rootobject
    {
        public bool success { get; set; }
        public int offset { get; set; }
        public Result result { get; set; }
    }

    public class Result
    {
        public bool error { get; set; }
        public int registers_count { get; set; }
        public int pages_count { get; set; }
        public int page { get; set; }
        public Datum[] data { get; set; }
    }

    public class Datum
    {
        public Product product { get; set; }
    }

    public class Product
    {
        public string sku { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string status { get; set; }
        public int qty { get; set; }
        public float price { get; set; }
        public float? list_price { get; set; }
        public float weight_gross { get; set; }
        public float weight_liquid { get; set; }
        public int height { get; set; }
        public int width { get; set; }
        public int length { get; set; }
        public string items_per_package { get; set; }
        public string brand { get; set; }
        public string ean { get; set; }
        public object ncm { get; set; }
        public Category[] categories { get; set; }
        public string[] variation_attributes { get; set; }
        public Variation[] variations { get; set; }
        public string[] images { get; set; }
        public Published_Marketplace published_marketplace { get; set; }
        public Marketplace_Offer_Links[] marketplace_offer_links { get; set; }
    }

    public class Published_Marketplace
    {
        public string ManairaDigital { get; set; }
    }

    public class Category
    {
        public string code { get; set; }
        public string name { get; set; }
    }

    public class Variation
    {
        public string sku { get; set; }
        public int qty { get; set; }
        public object EAN { get; set; }
        public float price { get; set; }
        public float list_price { get; set; }
        public object[] images { get; set; }
        public Variant[] variant { get; set; }
    }

    public class Variant
    {
        public string size { get; set; }
        public string color { get; set; }
    }

    public class Marketplace_Offer_Links
    {
        public string name { get; set; }
        public string href { get; set; }
    }
  • Related