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