'Decouple Json Deserialisation Keys > Properties mapping from Model. Is this possible?
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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IKomarovLeonid |
