5

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)

2
  • 2
    Try checking for JArray... Commented Feb 6, 2015 at 17:39
  • Post is as answer and I vote up, thanks Commented Feb 6, 2015 at 17:40

1 Answer 1

11

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

if (result is JArray)
Sign up to request clarification or add additional context in comments.

2 Comments

I was scraching my head for about 3 hours, and couldn't see that I missed the J.I guess it is way passed my sleeping time.Thanks again
LOL. No worries @BobSort, we've all been there :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.