简体   繁体   English

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

[英]Deserialize array Object using Newtonsoft Json.Net

I have following json string 我有以下json字符串

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

Which I need to parse in C#. 我需要在C#中解析。 My string might return error codes like this (or any other unknown error codes) 我的字符串可能会返回这样的错误代码(或任何其他未知的错误代码)

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

Or it might be just an empty array (no data) 或者它可能只是一个空数组(没有数据)

[]

Here is my code 这是我的代码

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

Problem 问题

In above code result is never of type Array . 在上面的代码中, result永远不会是Array类型。 in fact I have no way to check what is its type either (I tried typeof). 事实上我也无法检查它的类型(我试过typeof)。

Question

How can I check if I have an array in string and how can I check if it has objects in it (Please note, this is not a typed array) 如何检查字符串中是否有数组,如何检查其中是否有对象(请注意,这不是类型化的数组)

JsonConvert.DeserializeObject将您的Json转换为JArray而不是Array - 将您的检查更新为:

if (result is JArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM