[英]Extract JSONArray from JSONObject which does not contain double quote
我想从不包含双引号的 JSONObject 中提取 JSONArray。
HTTP响应实体如下。
{"asks":[["107.47649000",25.3039]],"bids":[["107.06385000",64.9317]],"isFrozen":"0","seq":298458396}
具体来说,我需要同时提取 107.4764900 和 25.3039。 但是,值 25.3039 不包含双引号。
我的代码在下面
public static void bid_ask () throws ClientProtocolException, IOException {
String queryArgs = "https://poloniex.com/public?command=returnOrderBook¤cyPair=USDT_ETH&depth=1";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(queryArgs);
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
System.out.println("Poloniex ETHUSDT");
//System.out.println(response.getStatusLine());
if (responseEntity != null) {
try (InputStream stream = responseEntity.getContent()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
JSONObject jsonObj = new JSONObject(line);
JSONArray tokenListBid = jsonObj.getJSONArray("bids");
JSONArray tokenListAsk = jsonObj.getJSONArray("asks");
JSONArray bid_element;
JSONArray ask_element;
double bid[] = new double[2];
double ask[] = new double[2];
System.out.println("Poloniex Bid");
if (tokenListBid != null) {
for (int i=0;i<2;i++){
bid_element = tokenListBid.getJSONArray(i);
bid[i]=bid_element.getBigDecimal(i).doubleValue();
System.out.println(bid[i]);
}
}
} //end while()
}
}
结果显示如下
Poloniex 出价 107.06385
线程“main” org.json.JSONException 中的异常:未找到 JSONArray[1]。
谢谢。
将内部数组视为 Object 数组并根据需要对它们进行类型转换。
这是解析“asks”部分的简化示例
JSONObject jsonObj = new JSONObject(line);
JSONArray asks = jsonObj.getJSONArray("asks").getJSONArray(0);
Double ask = 0.0;
for (Object o : asks) {
if (o instanceof String){
ask = Double.valueOf((String)o);
} else {
ask = (Double)o;
}
//do something with ask
}
更新
这是访问数据的另一种方式
JSONObject jsonObj = new JSONObject(line);
SONArray asks = jsonObj.getJSONArray("asks").getJSONArray(0);
Double price = Double.valueOf(asks.getString(0));
Double qty = Double.valueOf(asks.getDouble(1));
System.out.printf("Ask price: %.6f, quantity %.4f", price, qty);
这是我用来测试我的代码的字符串
String json = "{\"asks\":[[\"107.47649000\",25.3039]],\"bids\":[[\"107.06385000\",64.9317]],\"isFrozen\":\"0\",\"seq\":298458396}";
这是我得到的结果
询价:107.476490,数量 25.3039
[["107.06385000",64.9317]]
是一个1*2
数组, tokenListBid
是它。 所以你不能使用tokenListBid.getJSONArray(1);
将其编入索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.