Deserialize object using JSON.NET without the need for a container

妖精的绣舞 提交于 2019-12-11 09:57:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!