You need a custom JsonConverter and because your map object is created at runtime (I suppose), the converter has to be created at runtime as well.
Try:
var settings = new JsonSerializerSettings();
settings.Converters.Add(new PropertyNameFromMapTypeJsonConverter(map, typeof(Test2)));
var json = JsonConvert.SerializeObject(Data, settings);
The converter:
class PropertyNameFromMapTypeJsonConverter : JsonConverter
{
private readonly IDictionary<string, object> _mappings;
private readonly Type _targetType;
public PropertyNameFromMapTypeJsonConverter(object mapObj, Type targetType)
{
// mapobj is instance of Test1
// Use reflection to create a dictionary used as mappings between Test1 and 2
_mappings = TypeDescriptor.GetProperties(mapObj)
.OfType<PropertyDescriptor>()
.ToDictionary(prop => prop.Name, prop => prop.GetValue(mapObj));
_targetType = targetType;
}
public override bool CanConvert(Type objectType)
{
return objectType == _targetType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Do not support deserialize
throw new NotSupportedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = TypeDescriptor.GetProperties(value)
.OfType<PropertyDescriptor>()
.ToDictionary(prop => _mappings[prop.Name], prop => prop.GetValue(value));
serializer.Serialize(writer, dict);
}
}
JsonPropertyAttributeTest1? Please explain your question better.Dictionary?