Read Json without having to "know" the JAVA keys

2

The problem is that I need to inform the professions and I wanted the json reading to be automatic without having to report ocup[1] = "jornalista" . I would like the json reading to be automatic.

{
  "profissao": {
    "jornalista": [
      "escritor",
      "legal",
      "fotografo"
    ],
    "programador": [
      "focado",
      "exatas",
      "articulado"
    ],
    "maquinista": [
      "senai",
      "mecanico",
      "articulado"
    ]    
  }
}

My code is this

JSONObject jsonObject = (JSONObject) obj;

//System.out.println(jsonObject);
JSONObject locs = (JSONObject) jsonObject.get("profissao");
String[] ocup = new String[4];
ocup[0] = "jornalista";
ocup[1] = "programador";
ocup[2] = "maquinista";


ArrayList respostas = new ArrayList();

Scanner scan = new Scanner(System.in);
String v;
int cont = 0;
while(cont < ocup.length){
    JSONArray jorn = (JSONArray) locs.get(ocup[cont]);
    //System.out.println(jorn);

    int y= 0;
     while(y < jorn.size()){
            String name = jorn.get(y).toString();
            System.out.println("digite s ou n você é "+name);
            v = scan.nextLine();
            if(v.equals("s")) {
                respostas.add(name);
            }

            y++;
        }
     cont++;
}

System.out.println(respostas.size());
    
asked by anonymous 28.08.2017 / 13:29

1 answer

1

The JSONObject class has a method called keySet that lists the keys of an object:

JSONObject profissoes = (JSONObject) jsonObject.get("profissao");

chaves = profissoes.keySet();

for (String chave : chaves) {
  System.out.println(chave);
}
    
28.08.2017 / 13:59