mercredi 19 avril 2023

Mapping Dictionary

Decided to use Mapster instead of writing my own conversion/mapping methods. Haven't found anything that would suffice my use case on their github wiki.

I have an instance of Dictionary<string, string> where keys are property names of target type and values are string representations of that property value on the target type.

Here's an example of target type:

public sealed class TriggerSettings
{
    public bool ShouldRun { get; set; }
    public SimpleTriggerRecurringType RecurringType { get; set; } // enum
    public SimpleTriggerDayOfWeek DayOfWeek { get; set; } // enum
    public int Hour { get; set; }
    public int Minute { get; set; }
    public int Second { get; set; }
}

Keys in the dictionary may be incorrect and the key set may not contain all the target property names. I want to take all the valid property names and map string representations on according properties of the target type, but with a condition that I already have the target type instance and do not want to change properties, that are not present in the dictionary.

Is there a simple way to create such configuration with TypeAdapterConfig once or it can be only resolved at runtime for specific dictionary instance?

Previously I used my own simple method, that used reflection and looked like this

public static void ConvertAndMapKeyValuePairsOnObject<T>(T obj, IDictionary<string, string> propertyNameValuePairs)
{
    var properties = typeof(T).GetProperties(
        BindingFlags.Public |
        BindingFlags.NonPublic |
        BindingFlags.Instance);

    foreach (var property in properties)
    {
        if (!propertyNameValuePairs.ContainsKey(property.Name))
        {
            continue;
        }

        var converter = TypeDescriptor.GetConverter(property.PropertyType);
        var result = converter.ConvertFrom(propertyNameValuePairs[property.Name]);
        if (result is null)
        {
            continue;
        }

        property.SetValue(obj, result);
    }
}




Aucun commentaire:

Enregistrer un commentaire