Ignoring JSON Key Casing and Numbers as Strings when Deserializing with System.Text.Json

Download full source code.

I rarely deserialize JSON into objects via anything other than model binding in Web API applications. When doing it that way, the deserialization is very flexible with the casing of JSON key names not matching those in the model, and with numbers represented as strings.

For example, if you had Person model -

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }
}

You could send this JSON and it would bind correctly -

{
    "FiRsTnAmE": "Alan",
    "LASTname": "Adams",
    "agE": "25"
}

However, that is not the case when you use System.Text.Json.JsonSerializer.Deserialize(..) directly.

Using System.Text.Json to deserialize in a console app or library

When deserializing directly from a string or a file, e.g. JsonSerializer.Deserialize<Person>(myText), you should use JsonSerializerOptions to ignore the casing of the JSON keys and to allow numbers to be represented as strings in the JSON.

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

//snip..

var serializationOptions = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    NumberHandling = JsonNumberHandling.AllowReadingFromString
};

Then when deserializing, pass the serializationOptions to the Deserialize(..) method.

Person person = JsonSerializer.Deserialize<Person>(textToDeserialize, serializationOptions);

There are a couple of examples in the attached zip file.

Download full source code.

comments powered by Disqus

Related