使用JSON.NET反序列化对象,而无需使用容器 [英] Deserialize object using JSON.NET without the need for a container

查看:100
本文介绍了使用JSON.NET反序列化对象,而无需使用容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON.NET将从服务接收的JSON字符串反序列化为业务对象.

I am using JSON.NET to deseralize JSON strings that I receive from a service to my business objects.

我有一个很好的服务模式,可以将我所有的JSON字符串从给定的REST URL解析为一个对象,如下所示:

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.

例如,如果我得到以下JSON:

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",
        }
    ]
}

我的业务实体如下:

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

以上操作失败,因为JSON.NET期望使用容器对象.像这样:

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.

推荐答案

如果您这样重写LoadJSONToObject,就可以实现:

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

您的方法调用应为

LoadJSONToObject<List<Property>>("http://www.myapi.com/properties", "Properties");

这篇关于使用JSON.NET反序列化对象,而无需使用容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆