简体   繁体   中英

Deserialize array Object using Newtonsoft Json.Net

I have following json string

[
    {
        "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)

{"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).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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