JSON Value Could Not Be Converted to System.Int32: Fixes

The JSON value could not be converted to System.Int32 means the JSON value at the failing Path is not a whole number that fits in an int. Allow quoted numbers with JsonNumberHandling.AllowReadingFromString, make the property int? for null or empty values, or switch to long or decimal for big or decimal numbers. The message is the same for every cause, so it does not say what is wrong with the value. The Path at the end tells you which property failed, and the JSON value at that path tells you the fix. A number sent in quotes, an empty string, null, a decimal and a number larger than an int all produce this exact message, and each needs a different change. Find your value in the table below. If your error says System.String instead, see the System.String version of this error.

Animated table matching each JSON value that fails for an int property to its fix: quoted number uses AllowReadingFromString, empty string or N/A needs int? and a converter, null needs int?, a decimal needs decimal or double, and a very large number needs long. It is an illustration, not a screenshot.
Which fix matches which JSON value (illustration, not a screenshot).

Why the JSON value could not be converted to System.Int32

System.Text.Json is strict by default. A property typed int only accepts a JSON number that is a whole number inside the int range, from -2,147,483,648 to 2,147,483,647. Anything else throws a JsonException. This is the message for a value that is a string, with the path of the property:

The JSON value could not be converted to System.Int32. Path: $.EmployeeId | LineNumber: 0 | BytePositionInLine: 20.

I ran eight different bad values through JsonSerializer.Deserialize<Employee> on .NET 10.0.401, where Employee has one int EmployeeId property. All eight gave this same message, and only the byte position changed:

JSON value for EmployeeIdCauseFix
"1042"Number sent as a stringFix 1
"" or "N/A"Empty or non-numeric textFix 2
nullint cannot hold nullFix 2 (use int?)
12.5Decimal into a whole-number typeFix 3
3000000000Larger than int allowsFix 3
true or {"value":1}Wrong JSON type altogetherFix the JSON or the C# type

Because the message is identical, look at the JSON itself. Take the Path from the message, find that property in the payload, and match the value to a row above. The sibling error for strings has the same shape but different causes.

Fix 1: allow numbers sent in quotes

Some APIs and spreadsheets export ids and zip codes as "30301" even though they are numbers. You can tell the serializer to read them anyway. For one property, use an attribute:

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

var a = JsonSerializer.Deserialize<Address>("""{"ZipCode":"30301","Other":7}""")!;
Console.WriteLine(a.ZipCode);   // 30301

public class Address
{
    [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
    public int ZipCode { get; set; }
    public int Other { get; set; }
}

For the whole payload, set it on the options. The web defaults, which turn on camelCase names and quoted numbers together, do the same:

var opts = new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString };
var web  = new JsonSerializerOptions(JsonSerializerDefaults.Web);

Console.WriteLine(JsonSerializer.Deserialize<Employee>("""{"EmployeeId":"1042"}""", opts)!.EmployeeId);   // 1042
Console.WriteLine(JsonSerializer.Deserialize<Employee>("""{"employeeId":"1042"}""", web)!.EmployeeId);    // 1042

Both printed 1042. Two limits to know. First, the attribute only covers the property it sits on: in my run, a quoted value on the unmarked Other property still failed with the same message. Second, AllowReadingFromString does not accept an empty string, so "" still throws. That case is Fix 2. The options are described in Customize property names and values (Microsoft Learn).

Using an ASP.NET Core API? Request bodies are read with the web defaults, which I confirmed above accept quoted numbers, so if you still get the error the value is probably empty, null or not numeric. If you built your own JsonSerializerOptions with new(), you lost those defaults; use new(JsonSerializerDefaults.Web) instead. I did not run a hosted ASP.NET Core endpoint for this article.

Fix 2: empty strings, N/A and null

If the only problem is null, change int to int?. No converter is needed. For "" and "N/A", make the property nullable and add a converter that maps those texts to null. This is the converter I ran:

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

public sealed class LenientNullableIntConverter : JsonConverter<int?>
{
    public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        switch (reader.TokenType)
        {
            case JsonTokenType.Null:
                return null;
            case JsonTokenType.Number:
                return reader.GetInt32();
            case JsonTokenType.String:
                var text = reader.GetString();
                if (string.IsNullOrWhiteSpace(text) || text == "N/A") return null;
                if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) return value;
                throw new JsonException($"'{text}' is not a valid whole number.");
            default:
                throw new JsonException($"Unexpected token {reader.TokenType} for an integer.");
        }
    }

    public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
    {
        if (value is null) writer.WriteNullValue(); else writer.WriteNumberValue(value.Value);
    }
}

public class Lenient { public int? Code { get; set; } }

// var options = new JsonSerializerOptions { Converters = { new LenientNullableIntConverter() } };

Results with that converter on .NET 10:

{"Code":"7"}          -> 7
{"Code":""}           -> null
{"Code":"N/A"}        -> null
{"Code":null}         -> null
{"Code":5}            -> 5
{"Code":"abc"}        -> JsonException: 'abc' is not a valid whole number.
{"Code":3000000000}   -> JsonException: The JSON value could not be converted to System.Nullable`1[System.Int32]. Path: $.Code | ...

Decide first whether "N/A" really means no value. Turning every unreadable text into null hides bad data. The converter above fails loudly on "abc" on purpose. The converter API is explained in Write custom converters for System.Text.Json (Microsoft Learn), and a ready-made version for a plain int is in create a custom Int32Converter for System.Text.Json.

Fix 3: use the right number type

  • Amounts such as 49.99 or 12.5: use decimal (money) or double. A decimal in the JSON cannot go into an int.
  • Large ids such as 3000000000: use long. int stops at 2,147,483,647.
  • Codes that can start with zero, such as "02139": keep them as string. As a number, the leading zero is lost.
var ok = JsonSerializer.Deserialize<Typed>("""{"Id":3000000000,"Price":12.5,"Zip":"02139","Maybe":null}""")!;
Console.WriteLine($"{ok.Id} {ok.Price} {ok.Zip} {ok.Maybe?.ToString() ?? "null"}");
// 3000000000 12.5 02139 null

public class Typed { public long Id { get; set; } public decimal Price { get; set; } public string Zip { get; set; } = ""; public int? Maybe { get; set; } }

If you do not control the JSON and the sample is large, generate matching classes instead of guessing types. For the basics of reading and writing JSON, see serialization and deserialization with System.Text.Json.

‘Could not be converted to System.Nullable’ and long variants

The wording follows the property type. A long property gives System.Int64, and a nullable one gives System.Nullable`1[System.Int32], as in the last line of the converter results above. The causes and the fixes are the same, with the range of the type in place of the int range. Reading a number into a string property is the opposite problem, which gives Cannot get the value of a token type 'Number' as a string in some code paths; it is covered in the System.String article.

Error converting value {null} to type ‘System.Int32’ (Newtonsoft.Json)

Searches also land here from the Newtonsoft.Json message Error converting value {null} to type 'System.Int32'. Newtonsoft is more forgiving and tells you more. I ran the same inputs through Newtonsoft.Json 13.0.3:

JSON valueNewtonsoft.Json 13.0.3 result
nullError converting value {null} to type ‘System.Int32’. Path ‘EmployeeId’, line 1, position 18.
"1042"Reads as 1042, no error
""Error converting value {null} to type ‘System.Int32’. Path ‘EmployeeId’, line 1, position 16.
"N/A"Could not convert string to integer: N/A. Path ‘EmployeeId’, line 1, position 19.
12.5Input string ‘12.5’ is not a valid integer. Path ‘EmployeeId’, line 1, position 18.
3000000000JSON integer 3000000000 is too large or small for an Int32. Path ‘EmployeeId’, line 1, position 24.

The fix is the same idea: make the property int? or long, or clean the data. If a whole API still relies on Newtonsoft behavior, see add Newtonsoft JSON support in ASP.NET Core. The quoted-number case also explains why code that worked with Newtonsoft can fail after moving to System.Text.Json.

What was tested and what was not

  • Run on macOS with .NET SDK 10.0.401 (net10.0): all eight bad values against an int property, AllowReadingFromString (options and attribute), the web defaults, the converter and its seven inputs, the long, decimal and string mapping, and Newtonsoft.Json 13.0.3 with the same inputs. The outputs quoted above are the real ones.
  • Not tested: a running ASP.NET Core application (the web-defaults claim was checked on JsonSerializerOptions directly), source-generated serialization contexts, and other .NET versions.

Summary

  • The message is the same for every cause. Use the Path to find the property, then match its JSON value to the table.
  • Quoted number: AllowReadingFromString. Empty string, N/A or null: int? and a converter that returns null.
  • Decimal or very large number: change the C# type to decimal, double or long.

Found this useful?

Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

System.Int32 conversion FAQ

How do I fix ‘The JSON value could not be converted to System.Int32’?

Read the Path in the message, then match the JSON value at that path. Quoted numbers need JsonNumberHandling.AllowReadingFromString. Null or empty values need int? plus a converter. Decimals and values above 2,147,483,647 need decimal, double or long.

What does ‘Error converting value {null} to type System.Int32’ mean?

It is the Newtonsoft.Json message for null (or an empty string) going into an int property. Make the property int?, or clean the data.

What does ‘JSON integer is too large or small for an Int32’ mean?

The number is outside -2,147,483,648 to 2,147,483,647. Change the property to long. System.Text.Json reports the same case with the generic ‘could not be converted to System.Int32’ message.

Did this fix your error? Tell us in the comments which JSON value caused it.

2 thoughts on “JSON Value Could Not Be Converted to System.Int32: Fixes”

    1. Hi Abdulaziz- JsonOutput is the JSON data received which I have highlighted in the screenshot. System.Text.Json doesn’t convert such string field directly to Int without using custom Int32 converter.

Leave a Reply

Your email address will not be published. Required fields are marked *