Albert
Albert

Reputation: 11

Trying to convert JSONArray to JSONObject

Im getting the next error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.simple.JSONObject (org.json.simple.JSONArray and org.json.simple.JSONObject are in unnamed module of loader 'app')

The endpoint where im getting JSON is:

https://www.okex.com/api/spot/v3/instruments

I have searched about the error, I think the problem is that I am getting a JSONArray instead JSONObject, but I need to filter by key, as I need to get every "base_currency" from json, so i need JSONObject to filter through that key because cant do it with JSONArray because it has only filter by index. But I dont know how can do it

Below is the original code which is giving me the error:

    private String UrlBase = "https://www.okex.com/";
private URL url;
private String inline="";
private JSONObject jobj;
private JSONObject jobj1;
private Scanner sc;
private String Symbols = "api/spot/v3/instruments";
private String Param1= "base_currency";
private JSONArray arr;
private JSONArray arr1;
private JSONParser prs;
private HttpURLConnection conn;
private ArrayList Monedas = new ArrayList();
private Conexion conc = new Conexion();

public void CargarMonedasNuevasOkex() throws IOException {



    try {
        url = new URL(UrlBase+Symbols);
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 

    try {
        conn = (HttpURLConnection)url.openConnection();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    conn.setRequestMethod("GET");
    conn.connect(); 

    int responsecode = conn.getResponseCode(); 

    if(responsecode != 200) {

        throw new RuntimeException("HttpResponseCode: " +responsecode);

    }
    else{

        sc = new Scanner(url.openStream());

        while(sc.hasNext())
        {
            inline+= sc.nextLine();
        }
        sc.close();

        JSONParser parse = new JSONParser();
        try {

            jobj1 = (JSONObject) parse.parse(inline);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        arr1 = (JSONArray) jobj1.get(Param1);
        System.out.println(arr.get(0));
        for( int a=0; a<arr1.size(); a++ ) {

            jobj1 = (JSONObject) arr1.get(a);
        }
   }

}

Just edited with the correct code, the other was fine. sorry

Upvotes: 0

Views: 5261

Answers (2)

TanvirChowdhury
TanvirChowdhury

Reputation: 2445

try to use gson library(package com.google.gson) for this. use the following syntax

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.create().fromJson(yourJosnArray, yourObject.class)

if you have any date property you have to use

gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());

public class DateDeserializer implements JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        String date = element.getAsString();
        return TimeService.parseDate(date,"yyyy-MM-dd'T'HH:mm:ss");

    }
}

Upvotes: 1

Ahmad Sayeed
Ahmad Sayeed

Reputation: 354

Posting complete program so you won't miss any import. I executed this program and got the result. Also added json-simple dependencies.

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Example {
    private String UrlBase = "https://api.binance.com/";
    private URL url;
    private String inline = "";
    private JSONObject jobj;
    private Scanner sc;
    private String Symbols = "api/v1/exchangeInfo";
    private JSONObject jbj1;
    private JSONArray arr;
    private HttpURLConnection conn;

    public void CargarMonedasNuevasBinance() throws IOException {

        String Param1 = "symbols";
        String Param2 = "baseAsset";
        try {
            url = new URL(UrlBase + Symbols);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        conn.setRequestMethod("GET");
        conn.connect();
        int responsecode = conn.getResponseCode();
        if (responsecode != 200) {
            throw new RuntimeException("HttpResponseCode: " + responsecode);
        } else {
            sc = new Scanner(url.openStream());
            while (sc.hasNext()) {
                inline += sc.nextLine();
            }
            sc.close();
            JSONParser parse = new JSONParser();
            try {

                jobj = (JSONObject) parse.parse(inline);

            System.out.println(jobj.toString());
            org.json.JSONObject jsonObj = new    org.json.JSONObject(jobj.toString());
            System.out.println(jsonObj.toString());

            } catch (ParseException e) {
                e.printStackTrace();
            }
            arr = (JSONArray) jobj.get(Param1);
            for (int a = 0; a < arr.size(); a++) {

                jbj1 = (JSONObject) arr.get(a);
            }
        }
    }
}

Upvotes: 0

Related Questions