I'm looking for a way to pass a single string selector to get a value from hierarchical JSON. This selector could be id, location.name, or even deeper, it has to be dynamic.
I have this JSON:
{
"generatedAt": "2022-01-01 02:03:25",
"myitems": [
{
"id": "1795089",
"location": {
"name": "Myplace",
"countryCode": "DE"\
},
}
,
{
"id": "1795070",
"location": {
"name": "Roseplace",
"countryCode": "US"
},
}
],
"count": 2
}
I want to select nested values by a SINGLE selector. E.g. location.name. I want this because I want to store the selector in a single field in my database.
I have tried this:
Dim obj As JObject = JObject.Parse(json)
Dim jsonArray As JArray = DirectCast(obj("myitems"), JArray)
For Each item In jsonArray
item("id").Value(Of String) 'works
item("location")("name").Value(Of String) 'works
item("location.name").Value(Of String) 'does NOT work
Next
I considered storing the selector in my database like location.name and then when executing the selector in my code, first splitting that selector by ., and then build it like item(selectorpart(0))(selectorpart(1)).Value(Of String)
However, I have a lot of fields that I need to select and it would be a lot of extra code if I need to split each selector first. Also because many times my JSON is not as nested as above and I wouldn't need to split the selector at all.
How could I do this?
I checked here, but the described requirement seems different than mine. I checked here but it doesn't apply to nested structures. Also, I'm reading JSON feeds from different providers so I can't simply create a single class as was suggested in some other threads, and I don't want to have to map each feed structure to a class.