Reputation: 53
I am able to read the json file and store it in a JObject variable. I need to check for null values and ignore any segment that has null values. I was thinking of looping through the JObject but I don't know how i can access every segment/ key in the json below.
I think we can loop like this based on another question i saw on here:
foreach (var x in example) //example is the JObject in which json file is stored
{
string name = x.Key;
JToken value = x.Value;
}
But my json doesnt have keys. How do i go in every segment and check if name, description values are not null?
My json is :
{
"lorem ipsum Segment Groups":[
{
"name":"lorem ipsum",
"description":"lorem ipsum",
"segments":[
"Not Enrolled",
"Started Enrollment – Zipcode Lookup",
"Started Enrollment – Passed Flow Step 1",
"Started Enrollment – Passed Flow Step 2"
]
},
{
"name":"lorem ipsum",
"description":"Status Description",
"segments":[
"Moving in next 30 days",
"Moving in next 90 days",
"Not Moving"
]
},
{
"name":"lorem ipsum",
"description":"Interest description",
"segments":[
"Interested - Lots of Time Reading Many Pages",
"Interested - Lots of Time Comparing Products/Prices"
]
}
]
}
Thanks
Upvotes: 1
Views: 537
Reputation: 63387
By knowing the JSON structure, you can use various types with name formatted as JXxx
to read the values you want. However here there is one convenient way of selecting the tokens you want by using a json path. That way you can conveniently target the desired set of tokens and continue processing. I'm not so sure about the performance hit with that approach but you may take its trade-off (and if performance does matter, just try benchmarking it first).
The code can be simple like this:
//suppose your example is the loaded JObject
foreach (var group in example.SelectTokens("['lorem ipsum Segment Groups'][*]"))
{
var name = group["name"].Value<string>();
var desc = group["description"].Value<string>();
//check if they are null here ...
}
Note the way we escape keys or paths containing spaces by wrapping it inside ['']
. If your key does not need to be escaped, you can use it directly in the path.
Upvotes: 1
Reputation: 129827
Here is an example of how to loop through your JSON:
JObject obj = JObject.Parse(json);
JArray segmentGroups = (JArray)obj.Properties().FirstOrDefault()?.Value;
if (segmentGroups != null)
{
foreach (JObject group in segmentGroups.Children<JObject>())
{
string name = (string)group["name"];
string desc = (string)group["description"];
string[] segments = group["segments"]?.ToObject<string[]>();
Console.WriteLine("name: " + (name ?? "(null)"));
Console.WriteLine("description: " + (desc ?? "(null)"));
Console.WriteLine("segments: " + (segments != null ? "\n " + string.Join("\n ", segments) : "(null)"));
Console.WriteLine();
}
}
Fiddle: https://dotnetfiddle.net/kOJzaZ
Upvotes: 1