使用List反序列化为Object

时间:2012-01-17 15:06:31

标签: c# json list windows-phone-7 json.net

我试图将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?)

            }

提前致谢!

3 个答案:

答案 0 :(得分:4)

按如下方式更改您的班级定义

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

我偶尔使用的项目使用Json.Net。这是一个很棒的图书馆。 我会改用JsonConvert.DeserializeObject方法。

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

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

应该照顾它。