Newtonsoft.Json.Jsonreaderexception When making a POST

Asked

Viewed 767 times

1

I’m having trouble doing the post in my API my app up to register the object but then it locks the application and closes with this error of execution:

Newtonsoft.Json.Jsonreaderexception: Unexpected Character encountered while Parsing value: {. Path '', line 1, position 1.

   public async Task<int> AddFrutas(Fruta fruta)
            {
                HttpClient client = new HttpClient();
                var data = JsonConvert.SerializeObject(fruta);
                var content = new StringContent(data, Encoding.UTF8, "application/json");
                var response = await client.PostAsync("http://nivelamento.gopagoda.io/api/frutas", content);

                var result = JsonConvert.DeserializeObject<int>(response.Content.ReadAsStringAsync().Result);
                return result;

            }
  • You can add the serialized date value, please?

  • "name": "Banana", "vitamin": "E", @Aline

  • What about the value of Sponse?

  • @Aline, I managed to solve I already put the answer down.

1 answer

0


The problem was time to Deserialize the object, I switched to Dynamic and solved my problem.

public async Task<dynamic> AddFrutas(Fruta fruta)
{
    HttpClient client = new HttpClient();
    var data = JsonConvert.SerializeObject(fruta);
    var content = new StringContent(data, Encoding.UTF8, "application/json");

    var response = await client.PostAsync("http://nivelamento.gopagoda.io/api/frutas", content);

    var result = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);
    return result;

}
  • 1

    Rodrigo, it is good practice to add an "Httpstatuscode" check to ensure that your Request was "OK" for value deserialization.

  • Thanks for the tip @Eltonalmeidavieira.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.