c# - 使用 Newtonsoft Json.Net 反序列化数组对象

标签 c# json .net-4.0 json.net deserialization

我有以下 json 字符串

[
    {
        "itemtype": "note",
        "body": "some text"
    },
    {
        "itemtype": "list",
        "items": [
            {
                "item": "some text"
            },
            {
                "item": "some text"
            }
        ]
    },
    {
        "itemtype": "link",
        "url": "some link"
    }
]

我需要在 C# 中解析。我的字符串可能会返回这样的错误代码(或任何其他未知错误代码)

{"Error":"You need to login before accessing data"}

或者它可能只是一个空数组(没有数据)

[]

这是我的代码

public void ParseData(string inStr) {
    if (inStr.Trim() != "") {
        dynamic result = JsonConvert.DeserializeObject(inStr);
        if (result is Array) {
            foreach (JObject obj in result.objectList) {
                switch (obj.Property("itemtype").ToString()) {
                    case "list": // do something
                        break;
                    case "note": // do something
                        break;
                    case "link": // do something
                        break;
                }
            }
        } else {
            // ... read error messages
        }
    }
}

问题

在上面的代码中,result 永远不是 Array 类型。事实上,我也没有办法检查它的类型(我试过 typeof)。

问题

如何检查字符串中是否有数组以及如何检查其中是否包含对象(请注意,这不是类型化数组)

最佳答案

JsonConvert.DeserializeObject 会将您的 Json 转换为 JArray而不是 Array - 将您的支票更新为:

if (result is JArray)

关于c# - 使用 Newtonsoft Json.Net 反序列化数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28371519/

相关文章:

c# - Microsoft 更喜欢 False 值?

c# - 生成 RDP 配置文件问题

python - 预期关键数据类型不匹配 : S actual: L Dynamodb insert error with boto3

c# - 我们还应该使用服务器端网格还是 Javascript 网格?

javascript - 获取json数组中的最后一个元素

java - 为 Spring RestTemplate POST 获取 400 错误请求

c# - WCF 用户名密码验证器缓存

C# 程序使用 NPOI 编辑 excel(.xls) 的单元格值不起作用

c# - PDF 将零件编号转换为链接

c# - JavaScriptSerializer.Deserialize() 到字典中