问题
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.
I use the json.net reference but i cant't find what i'm looking for :(
my 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"
}
]
}
my root class for the json is:
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?)
}
Thanks in advance!
回答1:
Change your class definitions as follows
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; }
}
and deserialize
var rootObj = JsonConvert.DeserializeObject<RootObject>(myjson);
回答2:
Can you try the following code and report back any issues:
RootObject applications = JsonConvert.DeserializeObject<RootObject>(e.Result);
回答3:
A project I work on occasionally uses Json.Net. It's a wonderful library. I would use the JsonConvert.DeserializeObject method instead.
In your case I would try something like this:
var result = JsonConvert.DeserializeObject<RootObject>(yourJsonString);
That should take care of it.
来源:https://stackoverflow.com/questions/8896924/deserialize-to-object-with-a-list