简体   繁体   中英

Deserializing json into object and dictionary

I have a json below with nested data under "dependency" this could change at anytime. so it didnt make sense to create a class with individual strings to store the data. it could end up with more and more as time go on.

Sample Json

{
    "uniqueID": 13,
    "url": "www.abcde.com",
    "dependency": {
        "package1": "v1.0.3",
        "package2": "v5.4.2",
        "package3": "v12.3"
    },
    "assets": {
        "images": [
            "a.jpg",
            "b.jpg",
            "c.jpg",
            "d.jpg"
        ]
    }
}

My question is is there a way to deserialize the results into an object at the same time by creating a dictionary structure for "dependency" so I can get rid of the class and variables entirely?

My code that currently creates an object from the json.

    public class Dependency
    {
        public string package1 { get; set; }
        public string package2 { get; set; }
        public string package3 { get; set; }
    }

    public class Assets
    {
        public List<string> images { get; set; }
    }

    public class Root
    {
        public int uniqueID { get; set; }
        public string url { get; set; }
        public Dependency dependency { get; set; }
        public Assets assets { get; set; }
    }

    static void Main(string[] args){
        string jsonInput = File.ReadAllText(args[0]);
        Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(jsonInput);
    }

Try to change root to this

public class Root
    {
        public int uniqueID { get; set; }
        public string url { get; set; }
        public Dictionary<string, string> Dependency{ get; set; }
        public Assets assets { get; set; }
    }

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