用Java(非html)解析网页中的文本
我正在使用此代码从网站下载字符串:用Java(非html)解析网页中的文本,java,string,parsing,double,Java,String,Parsing,Double,我正在使用此代码从网站下载字符串: 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(
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。使用一个好的解析器,比如。还有一些很好的方法可用。响应是json。使用JavaJSON解析器并获取“high”元素的值。 其中一个java json解析器在()上可用
您收到的数据字符串称为
JSON
(JavaScript对象表示法)是一种轻量级数据交换格式。使用细粒度对数据进行编码和解码
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getString("high");