Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 599
AaA Avatar asked Feb 06 '15 17:02

AaA


People also ask

How do you serialize and deserialize an object in C# using JSON?

To serialize a . Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to . Net object using Deserialize<T> or DeserializeObject methods.

How do you serialize an array in JSON?

To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for. Json.NET will serialize the collection and all of the values it contains.

What is Jsonconvert?

Provides methods for converting between . NET types and JSON types.


1 Answers

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

if (result is JArray)
like image 180
petelids Avatar answered Sep 23 '22 21:09

petelids