字典 "Key" 和 "Value" 属性名称未按驼峰式序列化
Dictionary "Key" and "Value" properties names aren't being camel-case serialized
序列化 List<KeyValuePair<string, string>>
时,这是 JSON 我得到的:
[
{
"Key": "Mineplex",
"Value": "ULTRA"
}
]
但是,我希望它是 key
而不是 Key
,value
而不是 Value
。
我已经在使用 JsonNamingPolicy.CamelCase
。
我该怎么办?
也许使用以下 class?
public class JsonLowercaseKeyValuePair<TKey, TValue>
{
public JsonLowercaseKeyValuePair(TKey key, TValue value)
{
Key = key;
Value = value;
}
[JsonPropertyName("key")]
public TKey Key { get; set; }
[JsonPropertyName("value")]
public TValue Value { get; set; }
}
List<JsonLowercaseKeyValuePair<string, string>>
您可以这样使用Newtonsoft:
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
{
ProcessDictionaryKeys = true
}
};
var settings = new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(dictionaryListData, settings);
您可以在这里尝试一些解决方法,使用 Select
方法创建一个新的具有所需属性名称的匿名对象集合
var list = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Mineplex", "ULTRA")
};
var json = JsonSerializer.Serialize(list.Select(l => new { key = l.Key, value = l.Value }));
您将获得以下内容 JSON [{"key":"Mineplex","value":"ULTRA"}]
您也可以等到 GitHub 问题 #1197 得到修复以获得预期的行为
序列化 List<KeyValuePair<string, string>>
时,这是 JSON 我得到的:
[
{
"Key": "Mineplex",
"Value": "ULTRA"
}
]
但是,我希望它是 key
而不是 Key
,value
而不是 Value
。
我已经在使用 JsonNamingPolicy.CamelCase
。
我该怎么办?
也许使用以下 class?
public class JsonLowercaseKeyValuePair<TKey, TValue>
{
public JsonLowercaseKeyValuePair(TKey key, TValue value)
{
Key = key;
Value = value;
}
[JsonPropertyName("key")]
public TKey Key { get; set; }
[JsonPropertyName("value")]
public TValue Value { get; set; }
}
List<JsonLowercaseKeyValuePair<string, string>>
您可以这样使用Newtonsoft:
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
{
ProcessDictionaryKeys = true
}
};
var settings = new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(dictionaryListData, settings);
您可以在这里尝试一些解决方法,使用 Select
方法创建一个新的具有所需属性名称的匿名对象集合
var list = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Mineplex", "ULTRA")
};
var json = JsonSerializer.Serialize(list.Select(l => new { key = l.Key, value = l.Value }));
您将获得以下内容 JSON [{"key":"Mineplex","value":"ULTRA"}]
您也可以等到 GitHub 问题 #1197 得到修复以获得预期的行为