Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
778 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65929807/deserialize-nested-objects-in-json-and-assign-to-c-sharp-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

class Root
{
    public List<PackageCategory> PackageCategory;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...