【问题标题】:Exception not thrown while expected C# using Newtonsoft使用 Newtonsoft 的预期 C# 未抛出异常
【发布时间】:2021-09-07 13:57:40
【问题描述】:

我有一个需要属性的对象

public class EmailStructureRequestModel
{
    
    [JsonProperty(PropertyName = "Sender", Required = Required.Always)]
    public EmailSender Sender { get; set; }
    
    [JsonProperty(PropertyName = "to", Required = Required.Always)]
    public List<string> To { get; set; }
    
    [JsonProperty(PropertyName = "Cc")]
    public List<string> Cc { get; set; }
    
    [JsonProperty(PropertyName = "Bcc")]
    public List<string> Bcc { get; set; }
    
    [JsonProperty(PropertyName = "Content", Required = Required.Always)]
    public EmailContent Content { get; set; }
}

此对象应包含允许发送电子邮件的所有信息。 然后我尝试构建一个 eMailStructure 对象。为此,我使用 Newtonsoft.Json

using (StreamReader r = new StreamReader(filePath))
{
    string json = r.ReadToEnd();
    EmailStructureRequestModel emailStructure =
               JsonConvert.DeserializeObject<EmailStructureRequestModel>(json);
    ...
}

我的问题是 JsonConvert 没有正确反序列化 Json 字符串。从文件中提取的字符串被正确读取,但是这里的类型不匹配。

{
    "Sender": {
        "Email": "xxx@xxx.com",
        "Password": "pwd",
        "Server": "xxxxxx",
        "ServerProtocol": "ServerProtocol.ExchangeEWS",
        "ServerPort": 993,
        "Ssl": true
    },
    "To" : ["myMail@test.com", ""],
    "Cc" : "",
    "Bcc" : "",
    "Content": {
        "EmailObject": "Email test",
        "Message": "Hello World",
    }
}

这里的抄送属性是一个空字符串,而不是一个字符串列表。我希望这里有一个例外。 我通过做这样的肮脏事情解决了这个问题:

try
{
    Console.WriteLine(emailStructure.Cc.Count == 0);
}
catch (Exception e)
{
     throw new Exception("Oops something went wrong");
}

有没有更优雅的方式来做到这一点?我为那个解决方案感到羞耻......

【问题讨论】:

  • 我还没有尝试过,但是看看文档,JsonArrayAttribute 有帮助吗?

标签: c# json serialization json.net


【解决方案1】:

Json 数据在抄送字段中包含一个空对象。这会导致反序列化的列表为空。

如果您希望反序列化在这种情况下引发异常,则将您的 Cc 属性的 JsonProperty 属性更改为必需,但允许为 null。

[JsonProperty(PropertyName = "Cc", Required = Required.AllowNull)]
public List<string> Cc { get; set; }

这将使反序列化抛出异常。然后,Json 数据必须包含带有列表的 Cc。该列表仍然可以为空,但会反序列化为一个列表。

例如,这将正确反序列化为Cc 属性中的空列表:

{
    "Sender": {
        "Email": "xxx@xxx.com",
        "Password": "pwd",
        "Server": "xxxxxx",
        "ServerProtocol": "ServerProtocol.ExchangeEWS",
        "ServerPort": 993,
        "Ssl": true
    },
    "To" : ["myMail@test.com", ""],
    "Cc" : [],
    "Bcc" : "",
    "Content": {
        "EmailObject": "Email test",
        "Message": "Hello World",
    }
}

【讨论】:

  • 谢谢它的帮助......无论如何,在向应用程序发送数据时应该操作一些控件......
猜你喜欢
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
相关资源
最近更新 更多