Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The JSON value could not be converted to System.Int32

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?

like image 777
ali suleymanli Avatar asked Aug 23 '19 13:08

ali suleymanli


People also ask

Why JSON value could not be converted to Int32?

System.Text.Json.JsonException: ‘The JSON value could not be converted to System.Int32. This issue is more because the new .NET /ASP.NET Core 3.1 framework has removed the dependency on JSON.NET and uses it’s own JSON serializer i.e ‘ System.Text.Json ‘.

Why JSON cannot be converted to string in ASP NET?

System.Text.Json.JsonException: ‘The JSON value could not be converted to System.String. This issue is more because of the new .NET /ASP.NET Core 3.1 framework serializer which has removed the dependency on JSON.NET and uses it’s own JSON serializer i.e ‘ System.Text.Json ‘.

What is system JSON jsonexception?

System.Text.Json doesn’t deserialize non-string values like Int, Boolean and other primitives into string properties. System.Text.Json.JsonException: ‘The JSON value could not be converted to System.String

What is JSON serialization error in ASP NET Core?

Serialization/Deserialization in .NET Core or ASP.NET Core 3.1 or .NET 5.0 gives below or similar error, System.Text.Json.JsonException: ‘The JSON value could not be converted to System.Int32. InvalidOperationException: Cannot get the value of a token type ‘String’ as a number.


1 Answers

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();
like image 56
Edward Avatar answered Sep 20 '22 00:09

Edward