System.Text.Json.JsonException: The JSON value could not be converted to System.String
Today in this article, we will cover how to resolve errors like “The JSON value could not be converted to”
Issue Description
Serialization/Deserialization in .NET Core or ASP.NET Core 3.1 gives below or similar error,
System.Text.Json.JsonException: The JSON value could not be converted to System.String
System.Text.Json.JsonException: the json value could not be converted to system.datetime.
System.Text.Json.JsonException: the json value could not be converted to system.collections.generic.list
Description
I had below JSON type which includes Int32 and boolean fields,
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
Any non-string value conversion produces the above JsonException
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string EmployeeId { get; set; } public Address Address { get; set; } public string IsPermanant { get; set; } }
The below logic produces the error,
Customer empObject = JsonSerializer.Deserialize<Customer>(jsonOutPut);
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 its own JSON serializer i.e. ‘System.Text.Json‘.
There are known limitations in the System.Text.Json serializer which are as per specification and design.
Resolution 1 (Recommended)
These limitations can be overcome by using Custom StringConverter.
Please see this article on the StringConverter example.
You may want to customize the StringConverter further if needed to address any custom requirements.
Resolution 2:
Continue using Newtonsoft as is?
I was able to serialize the same using NewtonSoft(JSON.NET) without any issues.
In ASP.NET Core you can enable NewotnSoft at startup itself.
Similar approaches can be used fix similar issues that occurred for different data types.
Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
Happy Coding !!
Reference :
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.