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.
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;
}
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() }
};
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