簡體   English   中英

解析Java中的網頁文本(非HTML)

[英]Parse text from webpage in Java (not html)

我正在使用以下代碼從網站下載字符串:

static public String getLast() throws IOException {
    String result = "";
    URL url = new URL("https://www.bitstamp.net/api/ticker/");
    BufferedReader in = new BufferedReader(new InputStreamReader(
            url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        result += str;
    }
    in.close();
    return result;
}

當我打印此方法的結果時,這就是我得到的:

{"high": "349.90", "last": "335.23", "timestamp": "1384198415", "bid": "335.00", "volume": "33743.67611671", "low": "300.28", "ask": "335.23"}

這就是打開URL時顯示的內容。 這對我來說很好,但是如果有更有效的方法來執行此操作,請告訴我。

我需要提取的是335.23。 這個數字一直在變化,但是諸如“高”,“最后”,“時間戳”等詞始終保持不變。 我需要將335.23提取為雙精度。 這可能嗎?

編輯:

解決了

String url = "https://www.bitstamp.net/api/ticker/";
    try {
        JsonFactory factory = new JsonFactory();
        JsonParser jParser = factory.createParser(new URL(url));
        while (jParser.nextToken() != JsonToken.END_OBJECT) {

            String fieldname = jParser.getCurrentName();
            if ("last".equals(fieldname)) {
                jParser.nextToken();
                System.out.println(jParser.getText());
                break;
            }

        }
        jParser.close();

    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JarException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

這是JSON。 使用像Jackson一樣好的解析器。 也有很好的教程

響應是一個json。 使用Java JSON解析器並獲取“高”元素的值。 可以在( http://www.json.org/java/index.html )上找到一種Java json解析器

JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getString("high");

您收到的數據字符串稱為JSON編碼 JSON (JavaScript對象表示法)是一種輕量級的數據交換格式。 使用細粒度的簡單json編碼器和解碼器來編碼和解碼數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM