繁体   English   中英

使用C#反序列化复杂的JSON对象

[英]Deserialize complex JSON object using c#

我知道如何反序列化基本的Json对象。 我对嵌套对象有疑问; 例如,这是我要反序列化的json示例。

{
    "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"
}

现在, "data"具有未知数量的对象,可能是100、1000,或者仅仅是1,并且所有对象的名称不同。 我的最终目标是获取数据内部每个对象的信息。

我尝试了基本的json,但根本没有用。

无论如何,这就是我尝试过的...

我做了一个叫做数据的课

public class data
{
    public long id { get; set; }
    public string key { get; set; }
    public string name { get; set; }
    public string title { get; set; }
}

然后我做了另一个叫做测试的课

public class test
{
    /*
    I have also tried this, which works but then I don't know what to do with it and how to deserialize the information of it.
    //public Newtonsoft.Json.Linq.JContainer data { get; set; }
    */
    public List<List<data>> data { get; set; }
    public string type { get; set; }
    public string version { get; set; }
}

在我的驱动程序应用程序中

 string downloadedData = w.DownloadString(link);
 test t = JsonConvert.DeserializeObject<test>(downloadedData);

但这没有按我预期的那样工作。 任何帮助,将不胜感激。

您正在寻找字典。

使用它作为您的类定义:

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

这表明读取对象是有效的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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