I have the following...
JArray clients = (JArray)clientsParsed["objects"];
foreach (JObject item in clients.Children())
{
// etc.. SQL params stuff...
command.Parameters["@MyParameter"].Value = JTokenToSql(item["thisParameter"]);
}
JTokenToSql
looks like this...
public static object JTokenToSql(JToken obj)
{
if (obj.Any())
return (object)obj;
else
return (object)DBNull.Value;
}
I have tried ((JObject)obj).Count
also.. But doesn't seem to be working.
You can proceed as follows to check whether a JToken Value is null
JToken token = jObject["key"];
if(token.Type == JTokenType.Null)
{
// Do your logic
}
Try something like this to convert JToken to JArray:
static public JArray convertToJArray(JToken obj)
{
// if ((obj).Type == JTokenType.Null) --> You can check if it's null here
if ((obj).Type == JTokenType.Array)
return (JArray)(obj);
else
return new JArray(); // this will return an empty JArray
}
There is also a type - JTokenType.Undefined.
This check must be included in @Brian Rogers answer.
token.Type == JTokenType.Undefined
As of C# 7 you could also use this:
if (clientsParsed["objects"] is JArray clients)
{
foreach (JObject item in clients.Children())
{
if (item["thisParameter"] as JToken itemToken)
{
command.Parameters["@MyParameter"].Value = JTokenToSql(itemToken);
}
}
}
The is Operator checks the Type and if its corrects the Value is inside the clients variable.
Source: Stackoverflow.com