简体   繁体   中英

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;
        }

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

Using NewtonsoftJson

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

Using System.Text.Json

var products = JsonSerializer.Deserialize<Products>(jsonString);
public partial class Products
{
    [System.Text.Json.Serialization.JsonPropertyName("Products")]
    public IEnumerable<Product> ProductsProducts { get; set; }
}

if you have the json response, only use this site for convert Json to c# class

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class Product    {
        public int ProductID { get; set; } 
        public string Name { get; set; } 
        public string ProductNumber { get; set; } 
        public int ProductCategoryID { get; set; } 
        public string ProductCategory { get; set; } 
        public int ProductModelID { get; set; } 
        public string Description { get; set; } 
    }

    public class Root    {
        public List<Product> Products { get; set; } 
    }

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

or use visual studio option Edit-->Paste Special-->Paste JSON as Classes

 public class Rootobject
        {
            public Product[] Products { get; set; }
        }

        public class Product
        {
            public int ProductID { get; set; }
            public string Name { get; set; }
            public string ProductNumber { get; set; }
            public int ProductCategoryID { get; set; }
            public string ProductCategory { get; set; }
            public int ProductModelID { get; set; }
            public string Description { get; set; }
        }




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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM