如何从网站API获取的数据中获取密钥

时间:2016-10-11 21:16:34

标签: java json-simple

我目前正在使用Eclipse编写Java代码。我试图获得关键的价值"高"给出数据

{" high":" 639.00000"," last":" 634.94000"," timestamp" :" 1476220216"," bid":" 634.94000"," vwap":" 630.07099",&# 34;音量":" 7939.75947138","低":" 613.83000","问":" 636.50000 ","打开":" 616.37000"}

我从这个地址得到的:" https://www.bitstamp.net/api/v2/ticker/btcusd/"

到目前为止,我收到了这段代码:

package JsonSimpleExample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.*;



public class JsonSimpleExample {

    public static void main(String[] args) throws IOException {

        URL url = new URL("https://www.bitstamp.net/api/v2/ticker/btcusd/");

        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        System.out.println(br.readLine());

    }
}

一种可能的解决方案是将我从网站获得的数据写入文件,并将每个键,值对输入到散列映射中并调用该值,但这似乎非常冗余。有没有办法直接获取API给我的数据的值?

1 个答案:

答案 0 :(得分:0)

简单的你还需要添加json库。

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONObject;

/**
 *
 * @author BTACTC
 */
public class JsonExample {

    URL url;
    String str;
    Scanner scan;
    JSON json;

    public JsonExample() throws MalformedURLException, IOException {

        url = new URL("https://www.bitstamp.net/api/v2/ticker/btcusd/");

        scan = new Scanner(url.openStream());

        str = new String();

        while (scan.hasNext()) {
            str += scan.nextLine();
        }

        System.out.println(str);// checking the data is now in string

        JSONObject obj = new JSONObject(str);
        System.out.println(obj.getString("high"));;

    }

    public static void main(String[] args) throws IOException {

        JsonExample JE = new JsonExample();

    }

}