反序列化到带有列表的对象 [英] Deserialize to Object with a List
本文介绍了反序列化到带有列表的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将JSON响应字符串解析为我的类对象.我无法弄清楚,我需要一些帮助.
Im trying to parse an JSON response string to my class objects.. I can't figure this out and i need some help with this.
我使用json.net参考,但找不到我想要的东西:(
I use the json.net reference but i cant't find what i'm looking for :(
我的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; }
}
我的子类(应用程序列表):
my sub class (list of applications):
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; }
}
要解析它,我现在有以下代码:
To parse it i have the following code now:
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);
这篇关于反序列化到带有列表的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文