sorry folks. I'm pretty new to writing code...
I'm writing a powershell cmdlet in c# and it reaches out to an API and gets JSON as a response.
Depending on the call I make to an API, a JSON array or a single JSON object is returned
Sometiems, it can be
{"result": [
{
"id": "24095",
"hostid": "24094",
"name": "host1.fqdn.com",
"clustered": "false",
"type": "VM",
"ipaddress" : "192.168.1.184"
},
{
"id": "24097",
"hostid": "24096",
"name": "host2.fqdn.com",
"clustered": "true",
"type": "VM",
"ipaddress" : "192.168.1.185"
}
]
}
and sometimes it can be
{"result": {
"id": "24095",
"hostid": "24094",
"name": "host1.fqdn.com",
"clustered": "false",
"type": "VM",
"ipaddress" : "192.168.1.184"
}
}
I'm trying to figure out how using JSON.NET, i can figure out if the json returned has an object for "result" or an array for "result".
Based on the check,I'd like to call a method that prints out the object or array in a CSV format
I'm hoping to write a generic method that will print out all the keys as the CSV header and the values as rows for the CSV.
But the first thing I'm having trouble with is figuring out whether my JSON object has an Array or just an Object
I tried
JObject jsonres = JObject.Parse(strResponse);
JObject appobj = (JObject)jsonres.SelectToken("result");
Console.WriteLine(appobj.Type.ToString());
results in
Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.
when appobj["result"] is an array and works just fine and prints "Object" when appobj["result"] is a single object.