[英]Decouple Json Deserialisation Keys > Properties mapping from Model. Is this possible?
Using Net 6 and System.Text.Json
I have:使用 Net 6 和
System.Text.Json
我有:
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:我需要解析来自 Json 的传感器,所以我正在使用:
var result = JsonSerializer.Deserialize<Sensor>(json);
The use of JsonPropertyName
is because Sensor
properties names don't match Json keys.使用
JsonPropertyName
是因为Sensor
属性名称与 Json 键不匹配。
I am getting Sensors data from different APIs and each one uses different keys.我从不同的 API 获取传感器数据,每个 API 使用不同的密钥。
I could use a Model per API: SensorModelApi1
, SensorModelApi2
with different JsonPropertyName
values.我可以使用 Model 每 API:
SensorModelApi1
, SensorModelApi2
具有不同JsonPropertyName
值。
Then I would map each Sensor Model to Sensor class.然后我将 map 每个传感器 Model 到传感器 class。
Question问题
Would be possible to decouple the Keys / Properties mapping from Sensor class?是否可以将键/属性映射与传感器 class 分离?
Instead of using JsonPropertyName
I would have other strategy for mapping for each API avoiding having a SensorModel for each API.除了使用
JsonPropertyName
,我还有其他策略来映射每个 API,避免为每个 API 使用 SensorModel。
Does this make sense?这有意义吗?
You can try to use Newtonsoft json package instead, seems that [JsonProperty] will fix your issue.您可以尝试改用 Newtonsoft json package,似乎 [JsonProperty] 可以解决您的问题。 Docs: https://www.newtonsoft.com/json/help/html/serializationattributes.htm
文档: https://www.newtonsoft.com/json/help/html/serializationattributes.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.