Search code examples
c#jsondeserializationjson-deserialization

Deserializing JSON to a C# class returns null


I'm trying to deserialize a JSON file to a c# class. However, my deserialize method always returns null. My JSON file looks like this-

{
  "Products": [
    {
      "ProductID": 994,
      "Name": "LL Bottom Bracket",
      "ProductNumber": "BB-7421",
      "ProductCategoryID": 9,
      "ProductCategory": "Bottom Brackets",
      "ProductModelID": 95,
      "Description": "Chromoly steel."
    },
    {
      "ProductID": 995,
      "Name": "ML Bottom Bracket",
      "ProductNumber": "BB-8107",
      "ProductCategoryID": 9,
      "ProductCategory": "Bottom Brackets",
      "ProductModelID": 96,
      "Description": "Aluminum alloy cups; large diameter spindle."
    }
  ]
}

I'm trying to serialize it to below class-

public class Product
    {
        [JsonProperty("ProductID")]
        public long ProductId { get; set; }

        [JsonProperty("Name")]
        public string Name { get; set; }

        [JsonProperty("ProductNumber")]
        public string ProductNumber { get; set; }

        [JsonProperty("ProductCategoryID")]
        public long ProductCategoryId { get; set; }

        [JsonProperty("ProductCategory")]
        public string ProductCategory { get; set; }

        [JsonProperty("ProductModelID")]
        public long ProductModelId { get; set; }

        [JsonProperty("Description")]
        public string Description { get; set; }

        [JsonProperty("Color", NullValueHandling = NullValueHandling.Ignore)]
        public string Color { get; set; }
    }
    public partial class Products
    {
        [JsonProperty("Products")]
        public IEnumerable<Product> ProductsProducts { get; set; }
    }

And finally, I'm using this code to deserialize it, however it returns null for some reason. Can someone please help?

public Products Get()
        {
            var jsonString = IO.File.ReadAllText("ProductsData.json");
            var products = JsonSerializer.Deserialize<Products>(jsonString);
            
            return products;
        }

Solution

  • Cause

    You are using the JsonProperty attribute from the Netwonsoft.Json package, but the built-in .NET Core/5 deserializer from the System.Text.Json namespace.

    How do I know that? Newtonsoft.Json does not have a JsonSerializer.Deserialize overload which takes a single string, and .NET does not contain a JsonPropertyAttribute.

    Those two are not compatible. The .NET deserializer ignores your [JsonProperty("Products")] attribute, does not find a propery named ProductsProducts in your JSON and, thus, yields null for that property.


    Fix

    To use the deserializer from the Newtonsoft.Json package instead, replace

    var products = JsonSerializer.Deserialize<Products>(jsonString);
    

    with

    var products = JsonConvert.DeserializeObject<Products>(jsonString);
    

    Here is a working fiddle with your code: https://dotnetfiddle.net/27Tz4t