Search code examples
c#jsonparametersremap

Remap JSON parameter in c#


i have a json string that i want to remap the parameter AOID to BOID

{  'ID': '56',  'AOID': 'o747'}

ive tried the following but i just got the same output

    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);
    }

i get

"{  'ID': '56',  'AOID': '747'}"

but i am expecting to get

"{  'ID': '56',  'BOID': '747'}"

very new to c#....

thanks in advance


Solution

  • Given that your product22 value is already serialized you can do a simple replace on a string like this:

        private void button2_Click(object sender, EventArgs e)
        {
            string product22 = "{  'ID': '56',  'AOID': '747'}";
    
            string json = product22.Replace("'AOID'", "'BOID'");
    
            Console.WriteLine(json);
        }
    

    Hope it helps.