Search code examples
c#jsonjson.netautomapperautomapper-4

Mapping flat JSON/Dictionary to model (containing sub classes)


I want to turn a flat json string into a model, the destination class has subclasses, and the flat json has all of the sub class objects with prefix; like "{classname}.{property}".

{
    "FirstName": "Joey",
    "LastName": "Billy",
    "EmploymentDetails.JobTitle": "JobTitle",
    "EmploymentDetails.StartDate": "2015-01-01T00:00:00",
    "ContactDetails.HouseNumberName": "10",
    "ContactDetails.Road": "Road"
}

This is my destination class:

public class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual EmploymentDetails EmploymentDetails { get;set;}
    public virtual ContactDetails ContactDetails { get;set;}
}
public class EmploymentDetails {
    public string JobTitle { get; set; }
    public DateTime StartDate { get; set; }
}
public class ContactDetails {
    public string HouseNumberName { get; set; }
    public string Road { get; set; }
}

I tried the following:

public static void main() {
    var json = @"{""FirstName"": ""Joey"",""LastName"": ""Billy"",""EmploymentDetails.JobTitle"": ""JobTitle"",""EmploymentDetails.StartDate"": ""2015-01-01T00:00:00"",""ContactDetails.HouseNumberName"": ""10"",""ContactDetails.Road"": ""Road"",}";

    //try using AutoMapper
    Mapper.CreateMap<string,Person>();
    var personModel = Mapper.Map<Person>(json);
    //just returns null values

    //try using Newtonsoft
    personModel = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(json);
    //fills values but obviously returns no nested data
}

I know that Automapper has RecognizePrefix and RecognizeDestinationPrefix, but AutoMapper seems to only care if it's in the orignal object, and not a sub class.

Potentially I could take my JSON string and make it a Dictionary, but even then I don't know how to map it to a model with sub classes.

There was hope that I could have an infinite amount of sub classes and the JSON string could just map the flat JSON model to a model.


Solution

  • You can make a JsonConverter that does this in a generic way, using a ContractResolver to group and populate properties in the class being deserialized or its contained classes as appropriate.

    You didn't ask for serialization, only deserialization, so that's what this does:

    public class JsonFlatteningConverter : JsonConverter
    {
        readonly IContractResolver resolver;
    
        public JsonFlatteningConverter(IContractResolver resolver)
        {
            if (resolver == null)
                throw new ArgumentNullException();
            this.resolver = resolver;
        }
    
        public override bool CanConvert(Type objectType)
        {
            return resolver.ResolveContract(objectType) is JsonObjectContract;
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
    
            JObject jObject = JObject.Load(reader);
            var contract = (JsonObjectContract)resolver.ResolveContract(objectType); // Throw an InvalidCastException if this object does not map to a JObject.
    
            existingValue = existingValue ?? contract.DefaultCreator();
    
            if (jObject.Count == 0)
                return existingValue;
    
            var groups = jObject.Properties().GroupBy(p => p.Name.Contains('.') ? p.Name.Split('.').FirstOrDefault() : null).ToArray();
            foreach (var group in groups)
            {
                if (string.IsNullOrEmpty(group.Key))
                {
                    var subObj = new JObject(group);
                    using (var subReader = subObj.CreateReader())
                        serializer.Populate(subReader, existingValue);
                }
                else
                {
                    var jsonProperty = contract.Properties[group.Key];
                    if (jsonProperty == null || !jsonProperty.Writable)
                        continue;
                    if (jsonProperty != null)
                    {
                        var subObj = new JObject(group.Select(p => new JProperty(p.Name.Substring(group.Key.Length + 1), p.Value)));
                        using (var subReader = subObj.CreateReader())
                        {
                            var propertyValue = serializer.Deserialize(subReader, jsonProperty.PropertyType);
                            jsonProperty.ValueProvider.SetValue(existingValue, propertyValue);
                        }
                    }
                }
            }
            return existingValue;
        }
    
        public override bool CanWrite { get { return false; } }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    And then use it thusly:

            var resolver = new DefaultContractResolver();
            var settings = new JsonSerializerSettings { ContractResolver = resolver, Converters = new JsonConverter[] { new JsonFlatteningConverter(resolver) } };
    
            var person = JsonConvert.DeserializeObject<Person>(json, settings);
    

    Prototype fiddle.