http://stackoverflow.com/questions/38111298/json-net-deserialize-json-string-and-map-properties-to-different-property-names

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
					
public class Program
{
	public static void Main()
	{
		string json = @"
            {
                ""values"": {
                    ""details"": {
                        ""foo"": ""94"",
                        ""bar"": ""47"",
                        ""baz"": ""32"",
                        ""quux"": 1
                    },
                    count: 4
                }
            }";
		
		var map = new Dictionary<Type, Dictionary<string, string>>
		{
			{ 
				typeof(Details), 
				new Dictionary<string, string>
				{
					{"property1", "foo"},
					{"property2", "bar"},
					{"property3", "baz"},
					{"property4", "quux"}
				}
			}
		};
		
		var settings = new JsonSerializerSettings
		{
			ContractResolver = new DynamicMappingResolver(map)
		};
		
		var root = JsonConvert.DeserializeObject<RootObject>(json, settings);
		
		Console.WriteLine("property1: " + root.values.details.property1);
		Console.WriteLine("property2: " + root.values.details.property2);
		Console.WriteLine("property3: " + root.values.details.property3);
		Console.WriteLine("property4: " + root.values.details.property4);
	}
}

class DynamicMappingResolver : DefaultContractResolver
{
	private Dictionary<Type, Dictionary<string, string>> memberNameToJsonNameMap;
	
	public DynamicMappingResolver(Dictionary<Type, Dictionary<string, string>> memberNameToJsonNameMap)
	{
		this.memberNameToJsonNameMap = memberNameToJsonNameMap;
	}
	
	protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
	{
		JsonProperty prop = base.CreateProperty(member, memberSerialization);
		Dictionary<string, string> dict;
		string jsonName;
		if (memberNameToJsonNameMap.TryGetValue(member.DeclaringType, out dict) && 
			dict.TryGetValue(member.Name, out jsonName))
		{
			prop.PropertyName = jsonName;
		}
		return prop;
	}
}

public class Details
{
	public string property1 { get; set; }
	public string property2 { get; set; }
	public string property3 { get; set; }
	public int property4 { get; set; }
}

public class Values
{
	public Details details { get; set; }
	public int count { get; set; }
}

public class RootObject
{
	public Values values { get; set; }
}
;