How to convert json to object and put into a system.out.println?

Asked

Viewed 542 times

1

I have the following code that returns a JSON:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import classes_json.JSONObject;

 class Connection {

     private String resultado;
     private JSONObject js_object;
     private  JSONObject obj_kappauni1;



void conectar() throws IOException {

    final String ENDERECO = "http://dwarfpool.com/eth/api?wallet=0940f5fAEF2bba7e1e6288E4bc4E9c75ee334b97";
    //Passo por parametro o endereco no qual deve pegar o json
    URL url = new URL(ENDERECO);
    //Abro conexão usando a url do json, assim vai ser conectado
    URLConnection conexao = url.openConnection();
    //Ler valores da api
    InputStreamReader inStreamread = new InputStreamReader(conexao.getInputStream());
    //Guardar valores api em buffer
    BufferedReader buffread = new BufferedReader(inStreamread);
    //String que vai receber os valores gravados no buffer

    while ((resultado = buffread.readLine()) != null) {
        //Imprime o resultado
        System.out.println(resultado);

        js_object = new JSONObject(resultado);

    }
    //obj_kappauni1 = js_object.getJSONObject("kappauni1");
    // boolean alive = js_object.getBoolean("alive");
  //  System.out.println(alive);

    //Fecho gravação

    inStreamread.close();
    buffread.close();

}
}

Whenever I run the code up, it gives the following error:

{
Exception in thread "main" classes_json.JSONException: A JSONObject text must end with '}' at 1 [character 2 line 1]
    at classes_json.JSONTokener.syntaxError(JSONTokener.java:505)
    at classes_json.JSONObject.<init>(JSONObject.java:220)
    at classes_json.JSONObject.<init>(JSONObject.java:357)
    at Connection.conectar(Connection.java:33)
    at Main.main(Main.java:10)

The returning JSON is :

{
  "autopayout_from": "0.100", 
  "error": false, 
  "last_payment_amount": "0.10213405", 
  "last_payment_date": "Wed, 23 Aug 2017 03:57:19 GMT", 
  "last_share_date": "Sat, 26 Aug 2017 14:38:54 GMT", 
  "payout_daily": false, 
  "payout_request": false, 
  "total_hashrate": 205.15, 
  "total_hashrate_calculated": 211.58, 
  "wallet": "0x0940f5fAEF2bba7e1e6288E4bc4E9c75ee334b97", 
  "wallet_balance": "0.09611122", 
  "workers": {
    "kappauni1": {
      "alive": true, 
      "hashrate": 113.0, 
      "hashrate_below_threshold": false, 
      "hashrate_calculated": 140.58, 
      "last_submit": "Sat, 26 Aug 2017 14:38:54 GMT", 
      "second_since_submit": 149, 
      "worker": "kappauni1"
    }, 
    "kappauni2": {
      "alive": true, 
      "hashrate": 92.15, 
      "hashrate_below_threshold": false, 
      "hashrate_calculated": 71.0, 
      "last_submit": "Sat, 26 Aug 2017 14:38:20 GMT", 
      "second_since_submit": 183, 
      "worker": "kappauni2"
    }
  }
}

2 answers

1


First you should store the entire body of the HTTP response in a variable:

StringBuilder resultado = new StringBuilder();
String line = null;
while ((line = buffread.readLine()) != null) {
    resultado.append(line).append('\n');
}

After storing the body of the HTTP response in the variable resultado, you can use a library to do the conversion. A simple way is by using the library org.json. In your case, afterward of while:

JSONObject jsonConvertido = new JSONObject(resultado.toString());
String valorJson = jsonConvertido.get("ChaveDoJson");
System.out.println(valorJson);

If you want to work with a JSON the same way you would work with a Java object, I recommend using more robust libraries such as GSON, Jackson or Moshi. By using them, you can create Java classes that represent JSON and the library will be in charge of converting.

  • Opa, thanks a lot for the light, I could go a little further, but the problem now is that it returns syntax error from JSON, and I don’t know why. I updated the code, if you could just take a peek and tell me according to your experience :).

  • @Diegokappaun updated the response with the part of storing the response body

  • Did you read my reply and decide to edit yours to put the correct answer? Half wrong.

  • @Sorack 1 - if you notice, my original answer already said that it should store the answer in the variable. I figured he could do it himself. 2 - If you have noticed, he edited his question AFTER I made a suggestion. Your reply would be invalid without editing it (and my reply). 3 - Your answer is inefficient, since you use string concatenation within a loop. Hug. =)

  • Thank you very much, I learned to do the procedure, I was just a little short of time to come here. I thank everyone who helped me :).

1

The real problem is that you weren’t reading the buffer to the end. I’ve also made some improvements to your code to prevent variables from being unnecessarily created:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.stream.Collectors;
import org.json.JSONObject;

public class Connection {

  private static final String ENDERECO = "http://dwarfpool.com/eth/api?wallet=0940f5fAEF2bba7e1e6288E4bc4E9c75ee334b97";
  private JSONObject js_object;
  private JSONObject obj_kappauni1;

  private String conectar() throws IOException {
    URLConnection conexao;
    URL url;
    InputStreamReader is;
    String resultado;
    BufferedReader br;

    //Passo por parametro o endereco no qual deve pegar o json
    url = new URL(ENDERECO);
    //Abro conexão usando a url do json, assim vai ser conectado
    conexao = url.openConnection();
    //Ler valores da api
    is = new InputStreamReader(conexao.getInputStream());
    //Guardar valores api em buffer
    br = new BufferedReader(is);
    //String que vai receber os valores gravados no buffer
    resultado = br.lines().collect(Collectors.joining());
    //obj_kappauni1 = js_object.getJSONObject("kappauni1");
    // boolean alive = js_object.getBoolean("alive");
    //  System.out.println(alive);

    //Fecho gravação
    is.close();
    br.close();

    return resultado;
  }
}

Browser other questions tagged

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