使用JSON.Net将JSON反序列化为对象或数组 [英] Deserialize JSON as object or array with JSON.Net

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

问题描述

我想知道是否可以反序列化可以是对象或数组的JSON对象.

I want to know if it is possible to deserialize a JSON object that could either be an object or an array.

类似于此问题: Jackson反序列化对象或数组

但是使用JSON.Net.

But using JSON.Net.

示例

{
    "response": {
        "status":"success",
        // Could be either a single object or an array of objects.
        "data": {
            "prop":"value"
        }
        // OR
        "data": [
            {"prop":"value"},
            {"prop":"value"}
        ]
    }
}

推荐答案

您可以将模型中数据"的属性类型更改为动态或对象,并在运行时检查其是否为数组.

You can change the property type for "data" in your model to dynamic or an object and check if it is an array on run-time.

这是一个例子:

public class Response
{
    [JsonProperty("status")]
    public string Status { get; set; }
    [JsonProperty("data")]
    public dynamic Data { get; set; }
}


var response = JsonConvert.DeserializeJson<Response>(json);
.
.
.

Type responseDataType = response.Data.GetType();

if(responseDataType.IsArray) {
    // It's an array, what to do?
}
else {
    // Not an array, what's next?
}

这篇关于使用JSON.Net将JSON反序列化为对象或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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