This question of yours is very similar to this is another you posted.
Consider verifying the packages class documentation org.json
, mainly JSONObject
and JSONArray
. Even so, see if this answer below will help.
Again, let's consider your JSON, reproduced below:
{
"Ficha":[
{
"nome":"nome",
"sobrenome":"sobrenome",
"idade":"idade",
"endereco":"endereco",
"empresa":"empresa",
"telefones":[
{
"residencial":"residencial"
},
{
"celular":"celular"
}
]
}
]
}
We have an unnamed object that contains a array of Ficha
, so we will construct the reproduction of this JSON as a JSONObject
, like this:
final JSONObject json = new JSONObject(json);
After this we will recover the array from Ficha
, as follows:
final JSONArray fichas = json.getJSONArray("Ficha");
If we print the contents of fichas
using fichas.toString(2)
we will have the following output:
[{
"idade": "idade",
"endereco": "endereco",
"nome": "nome",
"sobrenome": "sobrenome",
"empresa": "empresa",
"telefones": [
{"residencial": "residencial"},
{"celular": "celular"}
]
}]
If you also want the array of telefones
you will have to recover JSONObject
Ficha
and then JSONArray
telefones
, something like this:
final JSONObject ficha = fichas.getJSONObject(i);
final JSONArray telefones = ficha.getJSONArray("telefones");
When we print the contents of telefones
using telefones.toString(2)
we will have the following output:
[
{"residencial": "residencial"},
{"celular": "celular"}
]
This is a complete example that generated the outputs shown:
final JSONObject json = new JSONObject(getJSON());
final JSONArray fichas = json.getJSONArray("Ficha");
System.out.println(fichas.toString(2));
final int size = fichas.length();
for (int i = 0; i < size; i++) {
final JSONObject ficha = fichas.getJSONObject(i);
final JSONArray telefones = ficha.getJSONArray("telefones");
System.out.println(telefones.toString(2));
}
EDITION
To retrieve only existing element names you can use the methods names()
or keys()
An example using names()
is this:
final JSONArray names = json.names();
final int nSize = names.length();
for (int i = 0; i < nSize; i++) {
final Object name = names.get(i);
System.out.println(name);
}
That will result in this output:
Tab
Already one using keys()
is this:
final Iterator<String> iKeysIterator = json.keys();
while (iKeysIterator.hasNext()) {
System.out.println(iKeysIterator.next());
}
That will result in the same output:
Tab
See if the keySet()
method is available also, if it is, you can use it as follows:
final Set<String> keys = json.keySet();
for (final String key : keys) {
System.out.println(key);
}