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 ...