Deserialize complex JSON object using c#

后端 未结 1 370
情书的邮戳
情书的邮戳 2020-12-22 09:35

I know how to deserialize basic Json object. I am having a problem with nested objects; for example, here is an example json i want to deserialize.

{
    \"d         


        
相关标签:
1条回答
  • 2020-12-22 09:56

    You are looking for a dictionary.

    Use this as your class definition:

    public class Rootobject
        {
            public Dictionary<string, DataObject> data { get; set; }
            public string type { get; set; }
            public string version { get; set; }
        }
        public class DataObject
        {
            public int id { get; set; }
            public string key { get; set; }
            public string name { get; set; }
            public string title { get; set; }
        }
    

    And this demonstrates that reading your object works:

    var vals = @"{
    
    ""data"": {
        ""A"": {
            ""id"": 24,
            ""key"": ""key"",
            ""name"": ""name"",
            ""title"": ""title""
        },
        ""B"": {
            ""id"": 37,
            ""key"": ""key"",
            ""name"": ""name"",
            ""title"": ""title""
        },
        ""C"": {
            ""id"": 18,
            ""key"": ""key"",
            ""name"": ""name"",
            ""title"": ""title""
        },
        ""D"": {
            ""id"": 110,
            ""key"": ""key"",
            ""name"": ""name"",
            ""title"": ""title""
        }
      },
    ""type"": ""type"",
    ""version"": ""1.0.0""
    }";
    var obj = JsonConvert.DeserializeObject<Rootobject>(vals);
    
    0 讨论(0)
提交回复
热议问题