简体   繁体   中英

deserialize nested objects in json and assign to c# list

I have a json which I am reading and trying to convert to list of PackageCategory

[
    {
        "PackageCategory": [
            {
                "Size": "xxx",
                "Dimension": {
                    "Height": "000.0",
                    "Length": "1200.0",
                    "Breadth": "3300.0"
                },
                "Cost": "10.0m"
            },

            {

                "Size": "yyy",
                "Dimension": {
                    "Height": "1200.0",
                    "Length": "1400.0",
                    "Breadth": "5500.0"
                },
                "Cost": "790.5m"

            },
            {

                "Size": "zzz",
                "Dimension": {
                    "Height": "2550.0",
                    "Length": "4030.0",
                    "Breadth": "1600.0"
                },
                "Cost": "8.5m"

            }
        ]
    }
]

I want to deserialize it to C# list object List

public class PackageCategory
    {
        public string Size { get; set; }
        public PackageSize Dimension { get; set; }
        public decimal Cost { get; set; }
}
public class PackageSize
    {
        public double Height { get; }
        public double Length { get; }
        public double Breadth { get; }
}

I am using below code but getting null values to the list object listObjects

using (StreamReader r = new StreamReader(@"\ListOfPackageCategory.json"))
            {
                string json = r.ReadToEnd();
                var listObjects = JsonConvert.DeserializeObject<List<packageCategory>>(json)
}

Also tried with

JavaScriptSerializer ser = new JavaScriptSerializer();
var listObjects = ser.Deserialize<List<PackageCategory>>(json);

This also didnt work Please help to find the solution

You need a Root object to deserialize:
JsonConvert.DeserializeObject<List<Root>> :

class Root
{
    public List<PackageCategory> PackageCategory;
}

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