0

I am trying to serialize/deseralize a vendor json file that contains both camel case and pascal case property names.

The resulting objects use Pascal case for its properties.

What's the proper way of dealing with this situation using System.Text.Json?

{
    "name": "test",
    "value": {
        "Quote": {
            "ask": 0,
            "bid": 0
        },
        "CreatedBy": "User"
    }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
Rushui Guan
  • 3,023
  • 1
  • 24
  • 26

2 Answers2

2

The easiest solution is to turn on case insensitivity

JsonSerializerOptions.PropertyNameCaseInsensitive

Gets or sets a value that determines whether a property's name uses a case-insensitive comparison during deserialization. The default value is false.

Example

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var mertle = JsonSerializer.Deserialize<blah>(bob, options);

Additional Resources

How to enable case-insensitive property name matching with System.Text.Json

By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties. To change that behavior, set JsonSerializerOptions.PropertyNameCaseInsensitive to true

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • Thanks. Technically correct answer for my original question, but it doesn't address serialization. I have updated my question with the new requirement. – Rushui Guan Feb 26 '21 at 13:30
0

Another way to solve this problem by normalizing the input json.

private static readonly Regex JsonKeyRegex = new Regex(@"(?m)^[ ]*([^\r\n:]+?)\s*:");
static string ToJsonWithCamelCasing(string jsonWithMixedCasing)
{
    var jsonKeys = JsonKeyRegex.Matches(jsonWithMixedCasing);
    var jsonWithCamelCasingBuilder = new StringBuilder(jsonWithMixedCasing);
    foreach (Match jsonKey in jsonKeys)
    {
        var from = jsonKey.Captures[0].Value;
        var startLetterIdx = from.IndexOf("\"") + 1;
        var to = from.Substring(0, startLetterIdx) + char.ToLowerInvariant(from[statrLetterIdx]) + from.Substring(startLetterIdx + 1);
        jsonWithCamelCasingBuilder.Replace(from, to);
    }

    return jsonWithCamelCasingBuilder.ToString();
}
  • This regex will find the keys in json (Test case)
    • The captured data contains some whitespaces at the front, like this: " \"Quote\":"
    • That's why we need to find the first letter of the json key (startLetterIdx)
  • In to we replace the first character of the json key to its lower variant.
    • (Yes I know it is a bit fragile)
  • Finally we use a StringBuilder to construct a new string with several replaces.
Peter Csala
  • 17,736
  • 16
  • 35
  • 75