pauldv69
4/5/2018 - 2:42 PM

JSON Custom Field Contract Resolver

JSON Custom Field Contract Resolver

using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class Program
{
    public static void Main()
    {
        string content = @"{
							""id"": 1,  
							""child"":   {
								""field1"": ""testing"",
								""field2"": ""another string"",
								""CustomFieldCustomer"": ""Customer Name"",
								""CustomFieldAssets"": [""asset1"", ""asset2"", ""asset3""]
								}
							}";

        var contractResolver = new FieldMappingContractResolver
        {
            FieldMappings =
                new Dictionary<string, string>() {{"Assets", "CustomFieldAssets"}, {"Customer", "CustomFieldCustomer"}}
        };

        var result = (Root)JsonConvert.DeserializeObject(content, typeof(Root), new JsonSerializerSettings { ContractResolver = contractResolver });

        Console.WriteLine("id: {0}", result.id);
        Console.WriteLine("child.field1: {0}", result.child.field1);
        Console.WriteLine("child.field2: {0}", result.child.field2);
        Console.WriteLine("child.Customer: {0}", result.child.Customer);
        Console.WriteLine("child.Assets.Count: {0}", result.child.Assets.Count);
    }
}

public class Root
{
    public int id { get; set; }
    public Child child { get; set; }
}

public class Child
{

    public dynamic field1 { get; set; }
    public string field2 { get; set; }
    public string Customer { get; set; }
    public List<string> Assets { get; set; }
    public Child()
    {
        Assets = new List<string>();
    }
}

public class FieldMappingContractResolver : DefaultContractResolver
{
    public Dictionary<string, string> FieldMappings;

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (FieldMappings.ContainsKey(property.PropertyName))
            property.PropertyName = FieldMappings[property.PropertyName];
        return property;
    }
}