How can I make Newtonsoft accept this property name with an underscore?

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
        public string Name { get; set; }

        public string Email { get; set; }

    public class Email
        public string Id { get; set; }

        public FromAddress FromAddress { get; set; }

    public static void Main()
        var str = "{\"from_address\":{\"name\":\"me\",\"email\":\"\"}, 
        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.

>Solution :

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

Try using the equivalent Newtonsoft attribute JsonProperty.


public FromAddress FromAddress { get; set; }

Leave a Reply