简体   繁体   中英

Error "is not a JSONObject": an API that returns this format in a String. How can I read and create objects from this with Java?

It's the request: https://api-pub.bitfinex.com/v2/candles/trade:1h:tBTCUSD/hist?limit=2 It's the response:

[[1607630400000,18399,18415,18450.367075,18399,279.63699634], [1607626800000,18290.48824022,18399,18400,18255,190.53601166]]

In another post, somebody told me that this is a Json... but when I try this:

public static void main(String[] args) throws IOException {
    String url = "https://api-pub.bitfinex.com/v2/candles/trade:1h:tBTCUSD/hist?limit=2";
    try {
        URL urlObj = new URL(url);
    
        HttpURLConnection conexion2 = (HttpURLConnection) urlObj.openConnection();
        conexion2.setRequestProperty("Accept-Language", "UTF-8");
        conexion2.setRequestMethod("GET");
        conexion2.connect();
        InputStreamReader in2 = new InputStreamReader(conexion2.getInputStream());
        BufferedReader br2 = new BufferedReader(in2);
        String output;
        output = br2.readLine();
        JSONArray array = new JSONArray(output);

        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

the Output is:

org.json.JSONException: JSONArray[0] is not a JSONObject.

Maybe I don't need to convert this String to Json? But how can I convert this String to Array or List?

Thanks!

As per your response

[[1607630400000,18399,18415,18450.367075,18399,279.63699634], [1607626800000,18290.48824022,18399,18400,18255,190.53601166]]

You do not have a json object inside the jsonArray, you have another json array. Here is a code snippet that will work. You have to get a JSONArray inside the look and then get the elements inside the inner array. This is my understanding of what you are trying to achieve.

String output = "[[1607630400000,18399,18415,18450.367075,18399,279.63699634], [1607626800000,18290.48824022,18399,18400,18255,190.53601166]]";
    JSONArray array = new JSONArray(output);
    for (int i = 0; i < array.length(); i++) {
        JSONArray arr = array.getJSONArray(i);
        for (int j = 0; j < arr.length(); j++) {
            if( arr.get(j) instanceof Double )
                System.out.println(arr.getDouble(j));
            else if( arr.get(j) instanceof Long )
                System.out.println(arr.getLong(j));
            else if( arr.get(j) instanceof String )
                System.out.println(arr.getString(j));
            else
                System.out.println(arr.get(j));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM