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

时间:2022-08-23 09:45:41

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#. My string might return error codes like this (or any other unknown error codes)

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

{"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. in fact I have no way to check what is its type either (I tried typeof).

在上面的代码中,结果永远不是Array类型。事实上我也无法检查它的类型(我试过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)

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

1 个解决方案

#1


11  

The JsonConvert.DeserializeObject will convert your Json to a JArray rather than an Array - update your check to:

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

if (result is JArray)

#1


11  

The JsonConvert.DeserializeObject will convert your Json to a JArray rather than an Array - update your check to:

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

if (result is JArray)