0

I have a JSON object that contains undetermined pattern and I need to get all keys of the json object and the sub-objects.

Here's an example of a JSON file:

{
  "users": {
    "address": [
      {
        "rue": "ruetest",
        "postal": 1111
      },
      {
        "rue": "ruetest",
        "postal": 2222
      }
    ],
    "type": "string",
    "user": [
      {
        "argent": 122,
        "id": 1,
        "nom": "user1",
        "prenom": "last1"
      },
      {
        "argent": 200,
        "id": 2,
        "nom": "user2",
        "prenom": "last2"
      },
      {
        "argent": 1205,
        "id": 3,
        "nom": "user3",
        "prenom": "last3"
      }
    ]
  }
}

and I need to have output like this:

[users,type,address,user,argent,id,nom,prenom] or something like this

3 Answers 3

1

I don't think there's really a built-in way to do this, but you could achieve your goal by making a function that does it. Something like (in pseudocode):

public Set getJsonKeys(JSON json) {
  Set s = new Set();
  for (Entry e : json.entrySet()) {
    s.add(e.key);
    if (e.value instanceof JSON) s.addAll(getJsonKeys(e.value));
  }
  return s;
}

I chose a Set rather than List to prevent duplicate entries. If you want to include keys of lists just add a check if e.value is a list and if so, iterate over elements and add getJsonKeys(element) for all elements.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for responding ,i already did somthing similaire but i hoped to find buily in function . I still need to get further and have somthing like this [users,users.type,users.address,users.user,users.user.argent,users.user.id,users.user.nom,users.user.prenom] or somthing similaire in order to be able to acces any value i want to acces
0

Have you tried the Genson Java Collections mode? It would give you easy generic access to arbitrary JSON files in java.

1 Comment

i can not use it because my json object does not have a generic type so i can not predefine a java class to serialise it
0

If you use the fastjson framework, I think you can use the following code to get all the keys:

JSONObject jsonObject = new JSONObject(jsonData);
Iterator keys = jsonObject.keys();
while (keys.hasNext()){
        String key = String.valueOf(keys.next());
    }

2 Comments

Does keys() recurse into all sub-objects or does it give you only the top-level keys?
It will give you all the keys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.