How to get objects from a Json array using Jsonarray in java?

Asked

Viewed 10,546 times

2

I’m having a little difficulty getting information from an Array of Json, as it is giving the error:

Exception in thread "main" json.org.Jsonexception: Jsonarray initial value should be a string or Collection or array.

The json output 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, I’d appreciate it if you’d shed some light.

MAIN CLASS

public class Main {

    public static void main(String[]args){

        Conection conection = new Conection();

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


    }



}

Class responsible for connecting and generating a Stringbuilder Return.

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 into object, here I cannot get the data from the Json Array 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 exit from 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
  • 1

    On which line is fired the exception?

  • The Jsonarray constructor expects a string, and you are passing an instance of Stringbuilder. Try : jArray = new JSONArray(json.toString());

  • I’ve updated you at this point, if you could just take a peek.

1 answer

4


You need to take the array inside the object...

Try this way:

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();
        }
    }
}

Exit:

--- 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
------------------------------------------------------------------------
  • I did this but can not find the object "date". I updated the code and the error.

  • I saw you’re getting one StringBuilder. Then you need to convert it with toString(). However, he does not find the "date" object strange. Put System.out.println, as my example, to confirm that json is coming in correctly.

  • I made the changes and put the output and error then saying that it did not find the object.

  • Dude, is there any cat in there... see that I remade my test using the same class Conection, ie the same json and is running ok.

  • 1

    Note that the answer has a different dependency than the one used in the question, since the answer is used: org.json.*, while the question makes use of the: json.org.*

  • Well observed Weslleytavares. Diego, you can use the same library that I used or the one you are using is a requirement of the project?

  • I can use, coming home I will test this way, but still have helped me enough, I thank everyone. I will give as solved.

Show 2 more comments

Browser other questions tagged

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