Exception not thrown while expected C# using Newtonsoft

Viewed 273

I have an object that requires Properties

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; }
}

This object should contain all information that allow to send emails. I try then to build a eMailStructure object. For this I use Newtonsoft.Json

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

My issue is that JsonConvert is not properly deserializing the Json string. The string extracted from the file is correctly read, but types here are not matching.

{
    "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",
    }
}

Here Cc property is an empty string, not a List of string. I would expect an exception here. I solved this by doing a dirty stuff like this:

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

Is there more elegant way of doing this ? I feel ashame of that solution ...

1 Answers

The Json data contains an empty object in the Cc field. This results in the deserialized list to be null.

If you want the deserialization to throw an exception in this case, then change JsonProperty attribute of your Cc property, to be required, but allow null.

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

This will make the deserialization throw an exception. The Json data must then contain a Cc with a list. The list can still be empty, but will be deserialized to a list.

For example, this will deserialize correctly to an empty list in the Cc property:

{
    "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",
    }
}
Related