The JSON value could not be converted to System.Int32

C#Jsonasp.net Core-Webapi

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

First you should create a JsonConverter for it:

using System;
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace sample_22_backend.Converters
{
    public class IntToStringConverter : JsonConverter<int>
    {
        public override int Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
                if (Utf8Parser.TryParse(span, out int number, out int bytesConsumed) && span.Length == bytesConsumed)
                {
                    return number;
                }

                if (int.TryParse(reader.GetString(), out number))
                {
                    return number;
                }
            }

            return reader.GetInt32();
        }

        public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }
}

Then use it this way on your model's properties:

[JsonConverter(typeof(IntToStringConverter))]
public int GenreId { set; get; }

Or you can add it globally:

services.AddControllers()
        .AddJsonOptions(options => 
                options.JsonSerializerOptions.Converters.Add(new IntToStringConverter()));

Solution 3 - C#

Starting in .NET 5, there is an option to deserialize numbers that are represented as JSON strings instead of throwing an exception.

using System.Text.Json;
using System.Text.Json.Serialization;

var options = new JsonSerializerOptions()
{
     NumberHandling = JsonNumberHandling.AllowReadingFromString |
     JsonNumberHandling.WriteAsString
};

// serialize
string denemeJson = JsonSerializer.Serialize<Deneme>(deneme, options);

// deserialize
Deneme denemeDeserialized = JsonSerializer.Deserialize<Deneme>(denemeJson, options);

Solution 4 - C#

In .NET CORE 3.X the serialize/deserialize process is done using System.Text.Json not Newtonsoft Json. Edward's answer did not work entirely for me:

  1. Installing from Nuget Manager Microsoft.AspNetCore.Mvc.NewtonsoftJson won't make step 2 to compile.
  2. Yes, add in Startup services.AddControllers().AddNewtonsoftJson(); - you will receive an error, AddNewtonsoftJson() not recognized.

At least this happened to me.

As a fix, uninstall what you've installed at step 1. In package manager console, run: Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.0.0-preview8.19405.7 . This worked for me.

Solution 5 - C#

Better parse the values to Integer and send data to Server Side application from your Client side application, This worked for me. Happy Coding!!

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

Solution 6 - C#

in js model, make sure your values are formatted as parseFloat();

Solution 7 - C#

There is an another way: just create a DTO with the type string for number types and convert it into the controller or to the type that you need.

Solution 8 - C#

May face this issue in .net core, You can change the datatype from int to int64

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionali suleymanliView Question on Stackoverflow
Solution 1 - C#EdwardView Answer on Stackoverflow
Solution 2 - C#VahidNView Answer on Stackoverflow
Solution 3 - C#HRKoderView Answer on Stackoverflow
Solution 4 - C#Cata HoteaView Answer on Stackoverflow
Solution 5 - C#AnglesvarView Answer on Stackoverflow
Solution 6 - C#MoustachioView Answer on Stackoverflow
Solution 7 - C#AlejandroView Answer on Stackoverflow
Solution 8 - C#GsantoView Answer on Stackoverflow