【发布时间】:2019-12-23 04:21:50
【问题描述】:
我有一个 json 字符串,我想将参数 AOID 重新映射到 BOID
{ 'ID': '56', 'AOID': 'o747'}
我尝试了以下方法,但我得到了相同的输出
public class CustomContractResolver : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public CustomContractResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{ "AOID", "BOID"},
};
}
protected override string ResolvePropertyName(string propertyName)
{
Console.WriteLine(propertyName);
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
private void button2_Click(object sender, EventArgs e)
{
string product22 = "{ 'ID': '56', 'AOID': '747'}";
string json =
JsonConvert.SerializeObject(product22,
new JsonSerializerSettings { ContractResolver = new CustomContractResolver() }
);
Console.WriteLine(json);
}
我明白了
"{ 'ID': '56', 'AOID': '747'}"
但我希望得到
"{ 'ID': '56', 'BOID': '747'}"
对 c# 非常陌生....
提前致谢
【问题讨论】:
-
在您的代码中,您正在调用 SerializeObject 方法并向其传递 JSON 字符串,但 SerializeObject 方法用于将对象转换为 JSON 字符串,而 Deserialize 方法用于将 JSON 字符串转换为对象。
标签: c# json parameters remap