How to convert JSON to Object and find an id (No Array) - JAVA

Asked

Viewed 155 times

0

I have a Json that does not contain an array and I need to get information from this Json. Follows the JSON

 {"_status":"sucesso","_mensagem":"Impressão em processamento","_dados":{"situacao":"PROCESSANDO","protocolo":"BkVglXYWQ"}}

What I’ve tried to do so far

JsonReader jsonReader = Json.createReader(new StringReader(jsonProtocolo));
    JsonObject jsonObject = jsonReader.readObject();
    JsonObject attributeDados = jsonObject.getJsonObject("_dados");
    JsonArray jsonArray = attributeDados.getJsonArray("_sucesso");

    String numeroProtocolo = jsonArray.getJsonObject(0).getString("protocolo");

    System.out.println("NUMERO PROTOCOLO: " + numeroProtocolo);

But I get nullPointer in the line String numeroProtocolo = jsonArray.getJsonObject(0). getString("protocol"); I tried that way too

 JSONObject obj = new JSONObject(jsonProtocolo);
    String numeroProtocolo = obj.getString("protocolo");

    System.out.println("NUMERO PROTOCOLO: " + numeroProtocolo);

However I get the error: Jsonobject["protocol"] not found

  • 2

    maybe this link can help you: http://theoryapp.com/parse-json-in-java/

  • Thanks for the reply friend, I tried so more unsuccessfully, I will update the question with the code I tried

  • 1

    I was able to solve thus Jsonobject obj = new Jsonobject(jsonProtocolo); String numeroProtocolo = obj.getJSONObject("_data"). getString("protocol");

  • yes, I was writing to do so as an answer =)

3 answers

4

The problem is here:

String numeroProtocolo = jsonArray.getJsonObject(0).getString("protocolo");

_dados is an object and not an array, try this:

String numeroProtocolo = jsonObject.getJSONObject("_dados").getString("protocolo");

JSON objects are surrounded by {}, while Arrays are surrounded by [].

3


I managed to solve the problem like this

 JSONObject obj = new JSONObject(jsonProtocolo);
    String numeroProtocolo = obj.getJSONObject("_dados").getString("protocolo");

If anyone needs this one;

1

JSONObject obj = new JSONObject(jsonProtocolo);
JSONObject dados = obj.getJSONObject("_dados");
String numeroProtocolo = dados.getString("protocolo");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.