Home > Software engineering >  Decouple Json Deserialisation Keys > Properties mapping from Model. Is this possible?
Decouple Json Deserialisation Keys > Properties mapping from Model. Is this possible?

Time:04-20

Using Net 6 and System.Text.Json I have:

public class Sensor {
  [JsonPropertyName("InstanceId")]
  public Int32 Id { get; set; }
  [JsonPropertyName("SensorName")]
  public String Name { get; set; }
  [JsonPropertyName("IsValid")]
  public Boolean Valid { get; set; }
}

I need to parse Sensors from Json so I am using:

var result = JsonSerializer.Deserialize<Sensor>(json);

The use of JsonPropertyName is because Sensor properties names don't match Json keys.

I am getting Sensors data from different APIs and each one uses different keys.

I could use a Model per API: SensorModelApi1, SensorModelApi2 with different JsonPropertyName values.

Then I would map each Sensor Model to Sensor class.

Question

Would be possible to decouple the Keys / Properties mapping from Sensor class?

Instead of using JsonPropertyName I would have other strategy for mapping for each API avoiding having a SensorModel for each API.

Does this make sense?

CodePudding user response:

You can try to use Newtonsoft json package instead, seems that [JsonProperty] will fix your issue. Docs: https://www.newtonsoft.com/json/help/html/serializationattributes.htm

CodePudding user response:

You can use automapper and add logic for mapping in separate file or configuration

var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Employee, EmployeeDTO>()
                    .ForMember(dest => dest.FullName, act => act.MapFrom(src => src.Name))
                    .ForMember(dest => dest.Dept, act => act.MapFrom(src => src.Department))
                );
  • Related