反序列化为具有列表的对象

本文关键字:对象 列表 反序列化 | 更新日期: 2023-09-27 18:20:37

我正在尝试将JSON响应字符串解析为我的类对象。。我想不通,我需要一些帮助。

我使用json.net参考,但找不到我要找的东西:(

我的json:

{
"@companyName": "Company Name",
"@version": "1.0",
"@generatedDate": "3/1/10 2:10 PM",
"application": [
    {
        "@name": "Application #1 name",
        "@apiKey": "1234",
        "@createdDate": "2010-03-01",
        "@platform": "Platform name"
    },
    {
        "@name": "Application #1 name",
        "@apiKey": "1234",
        "@createdDate": "2010-03-01",
        "@platform": "Platform name"
    }
]
}

json的根类是:

public class RootObject
{
    [JsonProperty]
    public string companyName { get; set; }
    [JsonProperty]
    public string version { get; set; }
    [JsonProperty]
    public string generatedDate { get; set; }
    [JsonProperty]
    public List<Application> application { get; set; }
}

我的子类(应用程序列表):

public class Application
{
    [JsonProperty]
    public string name { get; set; }
    [JsonProperty]
    public string apiKey { get; set; }
    [JsonProperty]
    public string createdDate { get; set; }
    [JsonProperty]
    public string platform { get; set; }
}

要解析它,我现在有以下代码:

      JObject obj = JObject.Parse(e.Result);
      applications = new RootObject
            {
                companyName = (string) obj["companyName"],
                version = (string) obj["version"],
                generatedDate = (string) obj["generatedDate"],
                application = ???????? (how to make a list here?)
            }

提前感谢!

反序列化为具有列表的对象

更改类定义如下

public class RootObject
{
    [JsonProperty("@companyName")]
    public string companyName { get; set; }
    [JsonProperty("@version")]
    public string version { get; set; }
    [JsonProperty("@generatedDate")]
    public string generatedDate { get; set; }
    public List<Application> application { get; set; }
}
public class Application
{
    [JsonProperty("@name")]
    public string name { get; set; }
    [JsonProperty("@apiKey")]
    public string apiKey { get; set; }
    [JsonProperty("@createdDate")]
    public string createdDate { get; set; }
    [JsonProperty("@platform")]
    public string platform { get; set; }
}

和反序列化

var rootObj = JsonConvert.DeserializeObject<RootObject>(myjson);

我工作的一个项目偶尔会使用Json.Net。这是一个很棒的库。我会使用JsonConvert.DeserializeObject方法。

在你的情况下,我会尝试这样的东西:

var result = JsonConvert.DeserializeObject<RootObject>(yourJsonString);

这应该能解决问题。

您可以尝试以下代码并报告任何问题吗:

RootObject applications = JsonConvert.DeserializeObject<RootObject>(e.Result);