Home > OS >  How to Loop on JSON JArray in c# when Array size becomes Zero
How to Loop on JSON JArray in c# when Array size becomes Zero

Time:04-13

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.
}

CodePudding user response:

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"]
}
  • Related