JSON.NET Case Insensitive Deserialization not working

15,095

Solution 1

You need to add an additional class:

public class MyRootNodeWrapper
{
    public MyRootNode MyRootNode {get;set;}
}

and then use:

MyRootNodeWrapperResponseObject = JsonConvert.DeserializeObject<MyRootNodeWrapper>(JsonString);

https://stackoverflow.com/a/45384366/34092 may be worth a read. It is basically the same scenario.

Also, change:

public MyData Data {get;set;}

to:

public MyData MyData {get;set;}

as per advice from @demo and @Guy .

Solution 2

This is the .NET Core built-in JSON library.

I found another way of doing it.. just in case, somebody is still looking for a cleaner way of doing it. Assume there exists a Movie class

    using System.Text.Json;

. . .

    var movies = await JsonSerializer.DeserializeAsync
        <IEnumerable<Movie>>(responseStream,
        new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        });

Startup Options:

You can also configure at the time of application startup using the below extension method.

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers()
            .AddJsonOptions(
                x =>
                {
                    x.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                });
    }

Solution 3

Simply add JsonProperty attribute and set jsonProperty name

public class MyRootNode
{
    [JsonProperty(PropertyName = "action")]
    public string Action {get;set;}
    [JsonProperty(PropertyName = "myData")]
    public MyData Data {get;set;}
}

public class MyData
{
    [JsonProperty(PropertyName = "name")]
    public string Name {get;set;}
}

UPD: and yes, add some base type as @mjwills suggest

Share:
15,095
CathalMF
Author by

CathalMF

Updated on June 07, 2022

Comments

  • CathalMF
    CathalMF almost 2 years

    I need to deserialize some JSON into my object where the casing of the JSON is unknown/inconsistent. JSON.NET is supposed to be case insensitive but it not working for me.

    My class definition:

    public class MyRootNode
    {
        public string Action {get;set;}
        public MyData Data {get;set;}
    }
    
    public class MyData
    {
        public string Name {get;set;}
    }
    

    The JSON I receive has Action & Data in lowercase and has the correct casing for MyRootNode.

    I'm using this to deserialize:

    MyRootNode ResponseObject = JsonConvert.DeserializeObject<MyRootnode>(JsonString);
    

    It returns to be an initialised MyRootNode but the Action and Data properties are null.

    Any ideas?

    EDIT: Added JSON

    {
       "MyRootNode":{
          "action":"PACT",
          "myData":{
             "name":"jimmy"
          }
       }
    }