I have a JSON String and convert it to JSONObject.
I want to get specific data from the JSONObject, and every time the JSONObject changes its structure, sometimes it’s in an array inside the JSON and sometimes not.
example:
the first time the JSON arrives like this
{
"id": "1",
"Name": "Jack",
"Value": {
"data": [
{"time": "2023", "age": "22"}
]
}}
the second time
{
"age": "22",
"time": "2023",
"Value": {
"data": [
{"Name": "Jack", "id": "1" }
]
}}
if I want to get the name in the first JSON
jsonObject.getString("Name")
and for the second one, I would use
jsonObject.getJSONArray("data").getJSONObject(0).getString("Name")
is there a way I can get the value dynamically regardless of where the keys are?
3
Answers
If your API come from an another team or an external provider, the first thing I would suggest to you, is to clearly define a contract. Otherwise, you can use the
isNull(String key)
method ofJSONObject
to check if the key exists or not.An example here:
If the JSON strings are always in a similar fashion then you can try a little parser method as provided below. It returns a Key/Value (String/Object) Map:
To use:
The console window will display:
You may consider library Josson.
https://github.com/octomix/josson
Deserialization
Query
*()
is a multi-level wildcard search. It returns the first resolvable element.