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

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 above code, 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 JSON that returns 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"
    }
  }
}
    
asked by anonymous 26.08.2017 / 16:55

2 answers

1

First you must 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 resultado variable, you can use a library to do the conversion. A simple way is to use the org.json library. In your case, after 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 in 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 do the conversion.

    
26.08.2017 / 19:16
1

The real problem is that you were not reading the% response% to the end. I've also made some improvements to your code to prevent variables from being created unnecessarily:

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;
  }
}
    
29.08.2017 / 02:22