1

I have to deserialize http response like this:

{
    "result": [
        "......"
    ],
    "plugins_versions": {
        "age": "agegender.AgeDetector",
        "gender": "agegender.GenderDetector",
        "detector": "facenet.FaceDetector",
        "calculator": "facenet.Calculator"
    }
}

I have the test snippet to simulate the deserialization process :

using System.Text.Json;
using System.Text.Json.Serialization;

var jsonOptions = new JsonSerializerOptions()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};

var jsonString = "{\"plugins_versions\": {\"age\": \"agegender.AgeDetector\"}}";
Console.WriteLine(jsonString);
var parsedText = JsonSerializer.Deserialize<Response>(jsonString, options: jsonOptions);

Console.WriteLine(parsedText.PluginsVersions.Age);

class Response
{
    public PluginVersion PluginsVersions { get; set; }
}

class PluginVersion
{
    public string Age { get; set; }
}

although the PropertyNamingPolicy is CamelCase, JsonSerializer cannot deserialize "plugins_versions" field, but If I use this:


    [JsonPropertyName("plugins_versions")]
    public PluginVersion PluginsVersions { get; set; }

JsonSerializer can deserialize json successfully. Is there a way to configure snake case to camel case (serialization)/deserialization in one place instead of specifying [JsonPropertyName("field_name")] manually ?

I tried to create custom naming policy like this:

using System.Text.Json;

namespace Test;

public class SnakeCaseToCamelCaseNamingPolicy : JsonNamingPolicy
{
    public override string ConvertName(string name)
    {
        return name
            .Split(new [] {"_"}, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => char.ToUpperInvariant(s[0]) + s.Substring(1, s.Length - 1))
            .Aggregate(string.Empty, (s1, s2) => s1 + s2); // this will convert snake case to camel case
    }
}

but it did not worked at all

  • 2
    `plugins_versions` is not camelCase but snake_case. Take a look at https://stackoverflow.com/questions/58570189/is-there-a-built-in-way-of-using-snake-case-as-the-naming-policy-for-json-in-asp – Alberto Dec 21 '22 at 09:42
  • Yeah, thanks it worked, I thought I am deserializing from snake case to camel case and indeed I am but I misunderstood that for serializing and deserializing, I should've used differend casings – Asadbek Sindarov Dec 21 '22 at 09:51
  • There is a `SnakeCaseNamingPolicy` in [this answer](https://stackoverflow.com/a/58576400) by [Muhammad Hannan](https://stackoverflow.com/users/4913418/muhammad-hannan) to [Is there a built in way of using snake case as the naming policy for JSON in ASP.NET Core 3?](https://stackoverflow.com/q/58570189). Does that answer your question? – dbc Dec 23 '22 at 18:58
  • 1
    @dbc Yes, It answered. I have used the same way to create `SnakeCaseNamingPolicy` as in the answer you mentioned – Asadbek Sindarov Dec 26 '22 at 04:53

0 Answers0