I'm retrieving data from an external API. One of their field names is "from_address". So I put that as the JsonPropertyName. But that doesn't work. I've recreated the issue in this fiddle.
public class Program
{
public class FromAddress
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("email")]
public string Email { get; set; }
}
public class Email
{
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("from_address")]
public FromAddress FromAddress { get; set; }
}
public static void Main()
{
var str = "{\"from_address\":{\"name\":\"me\",\"email\":\"me@me.me\"},
\"id\":\"the_one\"}";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Email>(str);
Console.WriteLine(result.FromAddress != null ? "something" : "nothing"); // nothing
Console.WriteLine(result.Id); // the_one
Console.WriteLine(result.FromAddress.Email); // throws a null reference exception
}
}
I know that the issue is the underscore, because if I replace "from_address" with "fromaddress" in my fiddle (in both the JsonPropertyName and the variable str) it works.