在 c# 中重新映射 JSON 参数

Remap JSON parameter in c#

我有一个 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# 很陌生....

提前致谢

您可以将进入一个 class 的对象反序列化,然后将其映射到另一个 class。

例如,您的第一个 class 将包含 Id 和 AOID。这也是您反序列化的class。第二个 class 将是 ID 和 BOID,这将是您将其映射到的 class。

鉴于您的 product22 值已经序列化,您可以像这样对字符串进行简单的替换:

    private void button2_Click(object sender, EventArgs e)
    {
        string product22 = "{  'ID': '56',  'AOID': '747'}";

        string json = product22.Replace("'AOID'", "'BOID'");

        Console.WriteLine(json);
    }

希望对您有所帮助。

您需要将一个对象传递给您的 SerializeObject 方法调用。 您可以像这样为您的测试构建一个匿名对象...

object inputObject = new {ID = "56", AOID = "747"};

如果您将按钮点击事件更新为此,您应该会得到您正在寻找的结果...

private void button2_Click(object sender, EventArgs e)
{
    object inputObject = new {ID = "56", AOID = "747"}; // create anonymous object

    string json =
    JsonConvert.SerializeObject(inputObject,
    new JsonSerializerSettings { ContractResolver = new CustomContractResolver() });
    Console.WriteLine(json);
}