【发布时间】:2020-06-24 07:50:08
【问题描述】:
我正在尝试使用 Jsonconverter 反序列化 json 字符串。我在 json 中有所有值,我还想提一下,那个特定的 json 是从 swagger 生成的,所以当我将有效负载发送到 API 时,它会将其映射到对象模型中。
但是,当我尝试将其反序列化为同一个对象时,一切都为空。我做错了什么?
这就是我反序列化的方式
EmailUrlDto testEmailUrlDto = JsonConvert.DeserializeObject<EmailUrlDto>(jsonString);
JSON 格式
{
"templateUrl": "https://some.blob.url.here.com",
"paramsHtml": [
{
"name": "{{miniAdmin}}",
"value": "Heyth is Admin!"
},
{
"name": "{{cliBuTree}}",
"value": "I`m a treeee!"
}
],
"from": "string",
"subject": "string",
"message": "string",
"isHtmlBody": true,
"recipients": [
{
"recipient": "some.name@lol.com"
}
],
"cCRecipients": [
{
"recipient": "string"
}
],
"bCCRecipients": [
{
"recipient": "string"
}
]
}
EmailUrlDto
public class EmailUrlDto : EmailDto
{
[Required]
[JsonPropertyName("templateUrl")]
public string TemplateUrl { get; set; }
[Required]
[JsonPropertyName("paramsHtml")]
public ParamsHtmlTemplateDto[] ParamsHtml { get; set; }
}
邮箱地址
public class EmailDto : Dto
{
[JsonIgnore]
public int Id { get; set; }
[JsonPropertyName("from")]
[MaxLength(250)]
public string From { get; set; }
[JsonPropertyName("subject")]
[Required]
[MaxLength(300)]
public string Subject { get; set; }
[JsonPropertyName("message")]
[Required]
public string Message { get; set; }
[JsonPropertyName("isHtmlBody")]
public bool IsHtmlBody { get; set; }
[JsonIgnore]
public EStatus EmlStatus { get; set; }
[JsonPropertyName("smtp")]
public SMTPConfigurationDto Smtp { get; set; }
[JsonIgnore]
public AttachmentDto[] Attachments { get; set; }
[JsonPropertyName("recipients")]
public ToRecipientDto[] Recipients { get; set; }
[JsonPropertyName("cCRecipients")]
public CcRecipientDto[] CCRecipients { get; set; }
[JsonPropertyName("bCCRecipients")]
public BccRecipientDto[] BCCRecipients { get; set; }
[JsonIgnore]
public LogDto[] Logs { get; set; }
}
【问题讨论】:
-
您用来命名属性的属性来自 System.Text.Json.Serialization 命名空间。 (例如 JsonPropertyName)。这是供框架在序列化/反序列化期间使用的。还添加 Newtonsoft 的 JsonProperty(string) 属性,它应该可以按预期工作。
-
@OguzOzgul 你的意思是在我目前在模型中的内容之上添加 JsonProperty(string) 吗?
-
是的,我想它会解决反序列化问题。
-
您可以将其发布为答案,以便如果您愿意我会接受它:)。谢谢
标签: c# json json.net jsonconvert jsonconverter