[英]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.