error“不是jsonobject”:以字符串形式返回此格式的api如何从java中读取这些内容?我需要根据这些信息创建对象

vaj7vani  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(244)

是请求:“https://api-pub.bitfinex.com/v2/candles/trade:1h:tbtcusd/hist?limit=2“响应:
[[1607630400000,18399,18415,18450.367075,18399,279.63699634], [1607626800000,18290.48824022,18399,18400,18255,190.53601166]]
在另一个帖子里有人告诉我这是一个json。。。但是当我尝试这个的时候:

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

输出为:
org.json.jsonexception:jsonarray[0]不是jsonobject。
我不需要把这个字符串转换成json?但如何转换为数组或列出此字符串?
谢谢!!!

wfveoks0

wfveoks01#

根据你的回答
[[1607630400000,18399,18415,18450.367075,18399,279.63699634], [1607626800000,18290.48824022,18399,18400,18255,190.53601166]]
在jsonarray中没有json对象,而是有另一个json数组。这里有一个代码片段可以工作。必须在外观中获得jsonarray,然后在内部数组中获得元素。这是我对你的理解。

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

相关问题