Search code examples
asp.net-corejson.netjson-deserialization

.NET Core - Json.NET Deserialisation Mapping


Is it possible to do mapping during the deserialization process of a JSON string to an object?

var resultObject = JsonConvert.DeserializeObject<ConfigItemGetResult>(result);

My JSON string is different from the object I want to deserialize to. So mapping has to happen. I'm trying to avoid making a model that maps 1 to 1 to the JSON string followed by mapping from object to object with for example AutoMapper.


Solution

  • Use Serialization Attributes for configuring your serialization mapping

    public class JsonTest
    {
        [JsonProperty(PropertyName = "SomePropNameFromJson")]
        public string SomeProp { get; set; }
        [JsonProperty(PropertyName = "SomeNested")]
        public SomeClass SomeClass { get; set; }
    }
        public class SomeClass
        {
             public SomeClass1 SomeClass1 { get; set; }
        }
    
        public class SomeClass1
        {
              public string text { get; set }
        }
    

    Here Json

    { "SomeProp":"value", "SomeNested":{ "SomeClass1":{ "text":"textvalue" } } }

    Json convert trying to convert text to object by prop name with value via reflection if them finds prop name in text they take value if prop name has different name in JSON you can specify it via [JsonProperty(PropertyName = "SomeNested")] if this attr not set by default it will try get by prop name and it whatever what property is, it some object(your nested objects) or basic type, it will trying to convert it automaticaly.