1

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

2

JsonPropertyName is from System.Text.Json so won't work correctly with Newtonsoft.

Try using the equivalent Newtonsoft attribute JsonProperty.

e.g.:

[JsonProperty("from_address")]
public FromAddress FromAddress { get; set; }
YungDeiza
  • 3,128
  • 1
  • 7
  • 32