0

I have two classes

// contains names/keys for JSON serialization
public class Mapping
{
    public string Id { get; set; }
    public string Name { get; set; }
}

// contains values for JSON serialization
public class Data
{
    public string Id { get; set; }
    public string Name { get; set; }
}

var map = new Mapping { Id = "Code", Name = "Tiltle" };
var data = new Data { Id = "Test1234", Name = "testname1234" };

so when data is serialized using the mapping from map, JSON should look like this

{
   "Code":"Test1234"
   "Tiltle":"testname1234"
}
5
  • Look at JsonPropertyAttribute Commented Mar 20, 2020 at 9:55
  • But your question is really not clear, what is Test1? Please explain your question better. Commented Mar 20, 2020 at 9:59
  • These are the 2 classes want to use one class values to define property name for other while converting to json Commented Mar 20, 2020 at 10:07
  • 1
    This seems like a really peculiar thing to do. Perhaps you're just better off using a Dictionary? Commented Mar 20, 2020 at 10:08
  • As @DavidG wrote, this feels like a xy problem. It's likely that you should represent this data using a dictionary internally, and then simply serialize the dictionary. Commented Mar 20, 2020 at 10:19

1 Answer 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.