I need to use JsonNamingPolicy.CamelCase
to serialize my object.
But when I use Dictionary
with [JsonExtensionData]
attribute, it seems something not work correctly.
Example Code.
public class Test
{
public Dictionary<string, object> Labels { get; set; } = new();
[JsonExtensionData]
public Dictionary<string, object> MetaInfo { get; set; } = new();
public Dictionary<string, object>? Nullable { get; set; } = null;
}
public class TestContent
{
public string? Value { get; set; }
}
System.Text.Json
var options = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
};
var test = new Test
{
Labels = new Dictionary<string, object>
{
{ "Test1", new TestContent{ Value = "TestContent1" } },
{ "Test2", new TestContent { Value = null } },
},
MetaInfo = new Dictionary<string, object>
{
{ "Test1", new TestContent{ Value = "TestContent1" } },
{ "Test2", new TestContent { Value = null } },
}
};
var result = JsonSerializer.Serialize(test, options);
System.Console.WriteLine(result);
Expected output
- Observe that the properties are named
"test1"
and"test2"
.
{
"labels":{
"test1":{
"value": "TestContent1"
},
"test2":{
}
},
"test1":{
"value": "TestContent1"
},
"test2":{
}
}
Actual output
- Observe that the properties are named
"Test1"
and"Test2"
instead.
{
"labels":{
"test1":{
"value": "TestContent1"
},
"test2":{
}
},
"Test1":{
"value": "TestContent1"
},
"Test2":{
}
}
You can see the JsonNamingPolicy.CamelCase
work correct on labels
, but work failed on Test1
and Test2
. Am I missing some settings?
When I change to Newtonsoft.Json
it works fine:
var contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
ProcessDictionaryKeys = true,
ProcessExtensionDataNames = true,
OverrideSpecifiedNames = false,
}
};
var settings = new JsonSerializerSettings
{
ContractResolver = contractResolver,
NullValueHandling = NullValueHandling.Ignore,
};
var result = JsonConvert.SerializeObject(test, settings);
System.Console.WriteLine(result);
// {"labels":{"test1":{"value":"TestContent1"},"test2":{}},"test1":{"value":"TestContent1"},"test2":{}}