Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore case when using TryGetProperty

I have an object of type JsonElement that contains data returned by an API. I want to get the value of a certain property but the problem is that TryGetProperty is case sensitive. Is there a way or a work around to get properties by name while ignoring case sensitivity?

Thank you.

like image 399
Veoxer Avatar asked Aug 26 '20 13:08

Veoxer


2 Answers

EnumerateObject will give you a list of all properties. You can loop through them and find the first one that matches the name ignoring case:

JsonElement value = null;
bool found = false;

var property = element.EnumerateObject()
                      .FirstOrDefault(p => string.Compare(p.Name, propName, 
                                                          StringComparison.OrdinalIgnoreCase) == 0);
if(property != null)
{
    value = property.Value;
    found = true;
}
like image 171
D Stanley Avatar answered Oct 06 '22 01:10

D Stanley


I just want to add this extra related information which might help others.

System.Text.Json.JsonSerializerOptions has a property called PropertyNamingPolicy

And the value can either be null or JsonNamingPolicy.CamelCase

So if it is set then C# PascalCase properties are converted to JavaScript camelCase names in the generated json. This can create unexpected problems when serializing and deserializing data as names do not match.

The problem can partly be overcome by setting PropertyNameCaseInsensitive = true in the options. Then you can serialize and deserialize in a case insensitive way.

However, if you are writing a custom JsonConverter then you may also need to find a property by the case sensitive name using JsonDocument.RootElement.TryGetProperty(). And for this you'll need to check for both the PascalCase and camelCase variations of the name to make it compatible with different options settings.

Lastly, JsonSerializerOptions has some presets that will automatically enable camelCase. For example, this JsonSerializerDefaults.Web preset automatically enables camelCase.

public JsonSerializerOptions Options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
    WriteIndented = true,
    Converters = { new MyCustomTypeConverter() }
};
like image 44
Roberto Avatar answered Oct 06 '22 00:10

Roberto