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)
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.
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.
Provides methods for converting between . NET types and JSON types.
The JsonConvert.DeserializeObject
will convert your Json to a JArray
rather than an Array
- update your check to:
if (result is JArray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With