Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading