The title is exactly what I meant
All the questions on Stackoverflow asks for whether if the json data is an object or array but what I'm looking for is to see if I can find out if the array is an array of primitive types or objects.
Currently, i already can identify if its an array or not, just that I'm unable to convert if it is not an array of strings.
This code is wrapped in a for loop, where it is (var comArrEl in comArr), where comArr is an array of strings. This array stores something like "gesmes:Envelope:Cube:Cube:@currency="USD"
Basically we're trying to write a universal API wrapper here.
// Identify if its an array or an object
if (token is JArray)
{
try
{
// Parse the comArrEl to an integer for index access
if (int.TryParse(comArrEl, out int index))
{
// Pump in the array
var dataList = token.ToObject<List<object>>();
// Is it the last?
if (comArrEl != last)
{
// let's work it out
// update the token
if (index >= 0 && index < dataList.Count)
{
token = JToken.Parse(JsonConvert.SerializeObject(dataList[index]));
}
}
// Yes its the last
else
{
var property = dataList[index];
// Number checks
// Make sure the datalist element we're targetting contains a proper value.
if (decimal.TryParse(property, out decimal val))
{
// Update it
_currencyPairComponentService.UpdatePairValue(component.Id, val);
}
}
}
// Incorrect comArrEl.
else
{
return false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
As you can see, the exception triggers on line 2.
Sample payload to code:
[
{
"@currency": "USD",
"@rate": "1.1354"
},
{
"@currency": "JPY",
"@rate": "128.31"
},
{
"@currency": "BGN",
"@rate": "1.9558"
},
{
"@currency": "CZK",
"@rate": "25.886"
},
{
"@currency": "DKK",
"@rate": "7.4630"
},
{
"@currency": "GBP",
"@rate": "0.88885"
},
{
"@currency": "HUF",
"@rate": "323.49"
},
{
"@currency": "PLN",
"@rate": "4.2826"
},
{
"@currency": "RON",
"@rate": "4.6528"
},
{
"@currency": "SEK",
"@rate": "10.1753"
},
{
"@currency": "CHF",
"@rate": "1.1328"
},
{
"@currency": "ISK",
"@rate": "139.40"
},
{
"@currency": "NOK",
"@rate": "9.6480"
},
{
"@currency": "HRK",
"@rate": "7.3990"
},
{
"@currency": "RUB",
"@rate": "75.8385"
},
{
"@currency": "TRY",
"@rate": "6.0453"
},
{
"@currency": "AUD",
"@rate": "1.5569"
},
{
"@currency": "BRL",
"@rate": "4.3692"
},
{
"@currency": "CAD",
"@rate": "1.5076"
},
{
"@currency": "CNY",
"@rate": "7.7848"
},
{
"@currency": "HKD",
"@rate": "8.8695"
},
{
"@currency": "IDR",
"@rate": "16344.08"
},
{
"@currency": "ILS",
"@rate": "4.2293"
},
{
"@currency": "INR",
"@rate": "80.0660"
},
{
"@currency": "KRW",
"@rate": "1264.39"
},
{
"@currency": "MXN",
"@rate": "23.2282"
},
{
"@currency": "MYR",
"@rate": "4.7165"
},
{
"@currency": "NZD",
"@rate": "1.6398"
},
{
"@currency": "PHP",
"@rate": "59.878"
},
{
"@currency": "SGD",
"@rate": "1.5520"
},
{
"@currency": "THB",
"@rate": "37.190"
},
{
"@currency": "ZAR",
"@rate": "15.6366"
}
]