I have an app that I would like to store some email setting in a json file.
The json file looks like:
{
"Id": 1,
"From": "[email protected]",
"Password": "mypassword",
"Port": 587,
"To": "[email protected]",
"SmtpAddress": "smtp.office365.com",
"TargetName": "STARTTLS/smtp.office365.com"
}
and C# code looks like :
public class EmailModel
{
[JsonProperty(nameof(Id))]
public int Id { get; set; }
[JsonProperty(nameof(To))]
public string To { get; set; }
[JsonProperty(nameof(From))]
public string From { get; set; }
[JsonProperty(nameof(Port))]
public int Port { get; set; }
[JsonProperty(nameof(Password))]
public string Password { get; set; }
[JsonProperty(nameof(SmtpAddress))]
public string SmtpAddress { get; set; }
[JsonProperty(nameof(TargetName))]
public string TargetName { get; set; }
}
and accessing it looks like:
public EmailModel EmailModel(int id)
{
var filePath = AppDomain.CurrentDomain.BaseDirectory;
using (var sr = new StreamReader(Path.Combine(filePath,"appsettings.json")))
{
string json = sr.ReadToEnd();
return JsonConvert.DeserializeObject<EmailModel>(json);
}
}
I have seen many posts for this, however none seem to work. I have added
var settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
in the EmailModel class and still all my values still end up null.
Update
debugging through this I see that sr.ReadToEnd() returns:
"{\r\n \"EmailModel\": {\r\n \"Id\": 1,\r\n \"From\": \"myemail\",\r\n \"Password\": \"myPassword\",\r\n \"Port\": 587,\r\n \"To\": \"myEmail\",\r\n \"SmtpAddress\": \"smtp.office365.com\",\r\n \"TargetName\": \"STARTTLS/smtp.office365.com\"\r\n }\r\n}\r\n"
}
Update 2: I get a reply from appsetting.json and when I change code from
var filePath = AppDomain.CurrentDomain.BaseDirectory;
var streamPath = Path.Combine(filePath, "appsettings.json");
string json = null;
using (var sr = new StreamReader(streamPath))
{
json = sr.ReadToEnd();
}
to:
var json = @"
{
""Id"": 1,
""From"": ""myEmail"",
""Password"": ""myPassword"",
""Port"": 587,
""To"": ""myEmail"",
""SmtpAddress"": ""smtp.office365.com"",
""TargetName"": ""STARTTLS/smtp.office365.com""
}";
my test doesnt fail.
File.Exists(streamReader'sFilePath)returnstrue?)nameofwith static strings then it works fine. I'd check that the file is loading correctly as KAI suggests. In particular it might be worth verifying the value of json before you are calling the deserialize. You should only get null if there is no json object at all. If it existed even if none of the properties matched you should get an object back and not null.