How to get objects from a Json Array using JsonArray in java?

0

I'm having a little difficulty getting information from a Json Array, because it's giving the error:

  

Exception in thread "main" json.org.JSONException: JSONArray initial value should be a string or collection or array.

The output of json is:

{"status":"OK","data":[{"worker":"kappauni1","time":1523537400,"lastSeen":1523537364,"reportedHashrate":113223366,"currentHashrate":102500000,"validShares":89,"invalidShares":0,"staleShares":5,"averageHashrate":68804012.34567899},{"worker":"kappauni2","time":1523537400,"lastSeen":1523537351,"reportedHashrate":108686214,"currentHashrate":110277777.77777778,"validShares":96,"invalidShares":0,"staleShares":5,"averageHashrate":62395061.72839507},{"worker":"kappauni3","time":1523537400,"lastSeen":1523537396,"reportedHashrate":211388916,"currentHashrate":175388888.8888889,"validShares":152,"invalidShares":0,"staleShares":9,"averageHashrate":120002314.8148148}]}

Follow the classes, thank you very much if you give a light.

CLASS MAIN

public class Main {

    public static void main(String[]args){

        Conection conection = new Conection();

        Convert convert = new Convert();
        convert.convertJsonForObject(conection.getJson());


    }



}

Class responsible for making connection and generating a return in StringBuilder.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

 class Conection
{

   private StringBuilder resultado = new StringBuilder();

    StringBuilder getJson()
    {

        String address = "https://api.ethermine.org/miner/0x0940f5fAEF2bba7e1e6288E4bc4E9c75ee334b97/workers";

        try {
            URL url = new URL(address);

            try {
                URLConnection connect = url.openConnection();

                connect.setRequestProperty("User-Agent", "Mozilla/4.0");
                InputStream in = connect.getInputStream();
                InputStreamReader inRead = new InputStreamReader(in);

                BufferedReader reader = new BufferedReader(inRead);

                String result;

                while((result = reader.readLine())!=null){

                    this.resultado = resultado.append(result);



                }




            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

            return resultado;
    }

}

Class responsible for converting Json to object, here I can not get the Json Array data correctly.

import json.org.JSONArray;
import json.org.JSONObject;

 class Convert {

     void convertJsonForObject(StringBuilder json){

        System.out.println(json);

         JSONObject obj = new JSONObject(json);
         JSONArray jArray = obj.getJSONArray("data");

        for(int i = 0; i < jArray.length(); i++){

            obj = jArray.getJSONObject(i);

            System.out.print(obj.toString());
        }

    }
}

The output of the error is:

{"status":"OK","data":[{"worker":"kappauni1","time":1523548800,"lastSeen":1523548743,"reportedHashrate":113155830,"currentHashrate":95833333.33333333,"validShares":83,"invalidShares":0,"staleShares":5,"averageHashrate":69709876.54320988},{"worker":"kappauni2","time":1523548800,"lastSeen":1523548779,"reportedHashrate":108667905,"currentHashrate":86944444.44444445,"validShares":75,"invalidShares":0,"staleShares":5,"averageHashrate":64443672.83950619},{"worker":"kappauni3","time":1523548800,"lastSeen":1523548783,"reportedHashrate":213519635,"currentHashrate":167611111.1111111,"validShares":145,"invalidShares":0,"staleShares":9,"averageHashrate":123407407.40740736}]}

Exception in thread "main" json.org.JSONException: JSONObject["data"] not found.
    at json.org.JSONObject.get(JSONObject.java:566)
    at json.org.JSONObject.getJSONArray(JSONObject.java:760)
    at Convert.convertJsonForObject(Convert.java:11)
    at Main.main(Main.java:10)

Process finished with exit code 1
    
asked by anonymous 12.04.2018 / 15:04

1 answer

3

You need to get the array that is inside the object ...

Try this:

package br.com.uniondata.projetodetestes;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
 *
 * @author Nilson
 */
public class Json {
    public static void main(String[] args) {
        Conection conection = new Conection();

        //StringBuilder json=new StringBuilder("{'status':'OK','data':[{'worker':'kappauni1','time':1523537400,'lastSeen':1523537364,'reportedHashrate':113223366,'currentHashrate':102500000,'validShares':89,'invalidShares':0,'staleShares':5,'averageHashrate':68804012.34567899},{'worker':'kappauni2','time':1523537400,'lastSeen':1523537351,'reportedHashrate':108686214,'currentHashrate':110277777.77777778,'validShares':96,'invalidShares':0,'staleShares':5,'averageHashrate':62395061.72839507},{'worker':'kappauni3','time':1523537400,'lastSeen':1523537396,'reportedHashrate':211388916,'currentHashrate':175388888.8888889,'validShares':152,'invalidShares':0,'staleShares':9,'averageHashrate':120002314.8148148}]}");
        StringBuilder json=conection.getJson();
        JSONObject obj=null;
        try{
            obj=new JSONObject(json.toString());
            System.out.println(obj.toString());
            JSONArray jArray = obj.getJSONArray("data");
            for(int i = 0; i < jArray.length(); i++){
                JSONObject o = jArray.getJSONObject(i);
                System.out.println(o.toString());
            }
        }catch(JSONException e){
            e.printStackTrace();
        }
    }
}

Output:

--- exec-maven-plugin:1.2.1:exec (default-cli) @ ProjetoDeTestes ---
{"data":[{"validShares":86,"staleShares":5,"lastSeen":1523551133,"currentHashrate":9.916666666666667E7,"averageHashrate":7.309104938271604E7,"invalidShares":0,"time":1523551200,"worker":"kappauni1","reportedHashrate":113159753},{"validShares":103,"staleShares":7,"lastSeen":1523551162,"currentHashrate":119500000,"averageHashrate":6.799305555555557E7,"invalidShares":0,"time":1523551200,"worker":"kappauni2","reportedHashrate":108694107},{"validShares":179,"staleShares":12,"lastSeen":1523551195,"currentHashrate":2.0755555555555555E8,"averageHashrate":1.3074074074074067E8,"invalidShares":0,"time":1523551200,"worker":"kappauni3","reportedHashrate":213535092}],"status":"OK"}
{"validShares":86,"staleShares":5,"lastSeen":1523551133,"currentHashrate":9.916666666666667E7,"averageHashrate":7.309104938271604E7,"invalidShares":0,"time":1523551200,"worker":"kappauni1","reportedHashrate":113159753}
{"validShares":103,"staleShares":7,"lastSeen":1523551162,"currentHashrate":119500000,"averageHashrate":6.799305555555557E7,"invalidShares":0,"time":1523551200,"worker":"kappauni2","reportedHashrate":108694107}
{"validShares":179,"staleShares":12,"lastSeen":1523551195,"currentHashrate":2.0755555555555555E8,"averageHashrate":1.3074074074074067E8,"invalidShares":0,"time":1523551200,"worker":"kappauni3","reportedHashrate":213535092}
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.569s
Finished at: Thu Apr 12 13:50:44 BRT 2018
Final Memory: 5M/123M
------------------------------------------------------------------------
    
12.04.2018 / 15:31