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"
}
}
}
By default Newtonsoft does case insensitive JSON deserialization and System. Text. Json does case sensitive JSON deserialization. Case sensitivity comes into play when a JSON string is being deserialized into an object.
JSON is case-sensitive. You must refer to SQL names in JSON code using the correct case: uppercase SQL names must be written as uppercase.
Jericho commented on Nov 25, 2017 Up until Json.net v9, the StringEnumConverter class was case insensitive and it was changed in v10. Here's the discussion explaining why it was changed and here's the commit released in v10 that changed the behavior to case-sensitive.
Refer to this answer that this is wanted according the JSON-RPC spec (keys are case sensitive!).
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
});
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;
});
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With