How to convert JSON to Object and find an id - JAVA

3

I need to convert a JSON to an object and navigate to an ID and just capture it. JSON Example:

"{"_status":"sucesso","_dados":{"_sucesso":[{"idintegracao":"BkmRboZmaaa","situacao":"SALVO","TituloNumeroDocumento":"01012020","TituloNossoNumero":"501","CedenteContaCodigoBanco":"748","CedenteContaNumero":"9999","CedenteConvenioNumero":"9999"}],"_falha":[]}}

I need to capture the idIntegration that is in _dados._sucesso [0] .idintegracao, and save in a string. What I've done so far:

 String jsonString = response.body().string();

        JSONObject jsonObjectBoleto = new JSONObject("{" + jsonString + "}");


        Iterator<String> iteratorBoletos = jsonObjectBoleto.keys();
        System.out.println("TO AQUI");

        System.out.println("TO AQUI NO WHILE " + iteratorBoletos.toString());
        JSONObject dadosBoleto = jsonObjectBoleto.getJSONObject(iteratorBoletos.toString());
        System.out.println("TO AQUI NO WHILE 2 " + iteratorBoletos.toString());
        Boleto boleto = new Boleto();
        System.out.println("DADOS DO BOLETO: " + dadosBoleto.getString("idintegracao"));

I tried to do this but without success:

      String jsonString = response.body().string();

        String json = ("{" + jsonString + "}");

        JSONObject obj1 = new JSONObject(json);

        String idIntegracao = obj1.getString("idintegracao");

        System.out.println("idIntegracao : " + idIntegracao);
    
asked by anonymous 19.06.2018 / 18:12

1 answer

1

You can use the Json rendering API available from java 1.8

Maven dependencies:

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
 </dependency>
 <dependency>
     <groupId>org.glassfish</groupId>
     <artifactId>javax.json</artifactId>
     <version>1.1</version>
</dependency>

After adding the libraries, retrieve Json in a String and create a JsonReader to read the String:

String jsonString = response.readEntity(String.class);
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));

Retrieve the JsonObject from jsonReader:

 JsonObject jsonObject = jsonReader.readObject();

Retrieve the JsonObject for the "_dados" attribute

 JsonObject attributeDados = jsonObject.getJsonObject("_dados");

Retrieve the JsonArray for the "_success" attribute

 JsonArray jsonArray = attributeDados.getJsonArray("_sucesso");

Finally recover the id

String idIntegracao = jsonArray.getJsonObject(0).getString("idintegracao");
    
20.06.2018 / 13:56