The JSON value could not be converted to System.Int32

ali suleymanli picture ali suleymanli · Aug 23, 2019 · Viewed 50.9k times · Source

I want to send data of object to my Web API. The API accepts a parameter of class, which properties are type of int and string.

This is my class:

public class deneme
{
   public int ID { get; set; }
   public int sayi { get; set; }
   public int reqem { get; set; }
   public string yazi { get; set; }
}

This is my JSON object:

{
   "id":0,
   "sayi":"9",
   "reqem":8,
   "yazi":"sss"
}

I want the api read the property "sayi" as integer. but because it cant, it gives the error:

The JSON value could not be converted to System.Int32. Path: $.sayi

How could I solve this problem?

Answer

Edward picture Edward · Aug 26, 2019

For Asp.Net Core 3.0, it uses System.Text.Json for serialization and deserialization.

For using old behavior, you could use Json.NET in an ASP.NET Core 3.0 project by referencing Json.NET support.

Short Answer:

  1. Install Microsoft.AspNetCore.Mvc.NewtonsoftJson which is preview version.
  2. Change to services.AddControllers().AddNewtonsoftJson();