1

I have two auto generated JSON data as shown below. I want to get all the data in Colors Tag. I Created a JArray of "Colors" and started looping on all data available, but when there is only one color available my code starts giving exceptions as "Colors" is not a JArray instead a JProperty. See sample code below.

What is the ideal way of handling this situation?

{
"UID":1234,
"Colors":["red", "blue", "green"]
}
{
"UID":1234,
"Colors":"green"
}
JObject jsonObject = (JObject)JsonConvert.DeserializeObject(jsonText, settings);

foreach (JObject reg in jsonObject["Colors"]) {
   // Write to console.
}
D-Shih
  • 44,943
  • 6
  • 31
  • 51

1 Answers1

1

First I would let your schema JSON "Colors" be an array because that can let your JSON be a strong schema.

if you can't modify the schema You can try to use JObject.Parse then use is to judge the type

var jsonObject = JObject.Parse(jsonText);
if (jsonObject["Colors"] is JArray)
{
    foreach (JObject reg in jsonObject["Colors"]) {
       // Write to console.
    }
}
else if(jsonObject["Colors"] is JToken)
{
    //jsonObject["Colors"]
}
D-Shih
  • 44,943
  • 6
  • 31
  • 51
  • For some reason JSON values that might be arrays or single items are really common, see [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/q/18994685/3744182) (51K views, +129 votes). I'd recommend doing `if (jsonObject["Colors"] is JArray array) { foreach (JObject reg in array) { } }` for performance reasons. – dbc Apr 12 '22 at 17:09