问题
I am using JSON.NET to deseralize JSON strings that I receive from a service to my business objects.
I have a nice Service pattern that parses all my JSON strings from a given REST URL to an object as follows:
private async Task<T> LoadJSONToObject<T>(string url)
{
//get data
var json = await GetResultStringAsync(url);
//deserialize it
var results = JsonConvert.DeserializeObject<T>(json);
return results;
}
The challenge that I am having is how do I use the above pattern with collections without creating a "container" class.
For example, if I am getting the following JSON back:
{
"Properties": [
{
"id": 1,
"name": "Property Name A",
"address": "Address A, City, Country",
},
{
"id": 2,
"name": "Property Name B",
"address": "Address B, City, Country",
}
]
}
And my business entity is as follows:
public class Property
{
[JsonProperty("id")]
public string ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("address")]
public string Address{ get; set; }
}
I would like to simply invoke my above method by calling:
LoadJSONToObject<List<Property>>("http://www.myapi.com/properties");
The above fails because JSON.NET is expecting a container object instead. Something like:
public class PropertyList
{
[JsonProperty("Properties")]
public List<Property> Properties { get; set; }
}
I think it's an overkill to create such a container and want to see if there is an elegant solution to do the above.
回答1:
You can accomplish that if you rewrite your LoadJSONToObject
like this:
private async Task<T> LoadJSONToObject<T>(string url, string rootProperty)
{
//get data
var json = await GetResultStringAsync(url);
if (string.IsNullOrWhiteSpace(rootProperty))
return JsonConvert.DeserializeObject<T>(json);
var jObject = JObject.Parse(json);
var parsedJson = jObject[rootProperty].ToString();
//deserialize it
return JsonConvert.DeserializeObject<T>(parsedJson);
}
Your method call should be
LoadJSONToObject<List<Property>>("http://www.myapi.com/properties", "Properties");
来源:https://stackoverflow.com/questions/20448379/deserialize-object-using-json-net-without-the-need-for-a-container