【发布时间】:2023-01-25 18:52:26
【问题描述】:
根据某些条件,我需要将 JSON 字符串反序列化为不同的模型,有时是模型 A,有时是模型 B。但是在模型 A 中有来自 System.Text.Json.Serialization 的 JsonPropertyName 属性,而在类 B 中有来自 @987654325 的 JsonProperty 属性@.问题是 JSON 字符串对应于实际的属性名称,而不是属性中给出的名称。我想让 JSON 序列化器(Newtonsoft 或 System.Text)忽略它自己的属性。那可能吗?
这是一个示例 JSON 字符串:
{
"PropertyOne" : "some value"
}
这是一个示例模型:
public class A
{
[JsonProperty("property_one")]
public string PropertyOne{ get; set; }
}
public class B
{
[JsonPropertyName("property_one")]
public string PropertyOne{ get; set; }
}
PS我不能改变模型
【问题讨论】:
-
我假设 Newtonsoft.Json 将忽略 System.Text.Json 属性,反之亦然,因此您可能需要在反序列化一个类时使用 Newtonsoft,在反序列化另一个类时使用 System.Text.Json。
-
听起来像是自定义合同解析器的工作。你可以在这里看到一个有点相关的例子:stackoverflow.com/a/20639697/625594
标签: c# .net json.net system.text.json