DEV Community

Cover image for Ignoring case and underscore on JSON deserialization in C#
Talles L
Talles L

Posted on

Ignoring case and underscore on JSON deserialization in C#

For ignoring case, it's a matter of creating and using a JsonSerializerOptions. For the underscore, there's no out-of-the-box approach other than set it with JsonPropertyName:

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

public static class Program
{
    public static void Main(string[] args)
    {
        var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
        var jsonString = @"{
          ""title"": ""Mario"",
          ""description"": ""Video game character"",
          ""extract"": ""Mario is a fictional character in the Mario video game franchise, owned by Nintendo and created by Japanese video game designer Shigeru Miyamoto. Acting as the company's mascot, as well as being the eponymous protagonist of the series, Mario has appeared in over 200 video games since his creation. Depicted as a short, pudgy, Italian plumber who resides in the Mushroom Kingdom, his adventures generally center upon rescuing Princess Peach from the Koopa villain Bowser. Mario's fraternal twin brother and sidekick is Luigi."",
          ""extract_html"": ""<p><b>Mario</b> is a fictional character in the <span><i>Mario</i> video game franchise</span>, owned by Nintendo and created by Japanese video game designer Shigeru Miyamoto. Acting as the company's mascot, as well as being the eponymous protagonist of the series, Mario has appeared in over 200 video games since his creation. Depicted as a short, pudgy, Italian plumber who resides in the Mushroom Kingdom, his adventures generally center upon rescuing Princess Peach from the Koopa villain Bowser. Mario's fraternal twin brother and sidekick is Luigi.</p>""
        }";

        var summary = JsonSerializer.Deserialize<Summary>(jsonString, jsonOptions);
    }
}

public class Summary
{
    public string Title { get; set; }

    public string Description { get; set; }

    public string Extract { get; set; }

    [JsonPropertyName("extract_html")]
    public string ExtractHtml { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

If you feel like setting the JsonPropertyName for each needed property is too cumbersome, I believe you can handle it with a JsonNamingPolicy (but I'm yet to try it myself).

Top comments (0)