简体   繁体   中英

Query a JSON Object in Java by index

In Java, is there a way to retrieve a piece of information from a JSON object by index? I am accessing a financial data table on quandl and want to return the most recent mortgage rate posted in the table. The key is the date the rate was posted in string form. The key for the most recent data will change weekly but the data I want will always be the first key-value pair in the table.

I was able to do this in JavaScript in about 5 minutes. But it seems more cumbersome in Java. Below is the iteration of my code that seems to be closest to getting me where I want to go. I am able to return the first key-value pair set in the table as an object in Java, which is ... ["2017-12-14",3.93]. The final step is eluding me. How do I grab the 3.93 and return that? Or is there a better way to go about this?

double baseRate = 0.0;

default double getBaseRate() throws MalformedURLException {

    try {
        // make a GET request
        URL url = new URL("https://www.quandl.com/api/v3/datasets/FMAC/30US.json?api_key=-c-s9zf8s1NdLbhVin1p");
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();
        InputStreamReader is = new InputStreamReader((InputStream) request.getContent());

        // Convert response stream to a JSON object
        JsonReader reader = Json.createReader(is);
        JsonObject obj = reader.readObject();
        reader.close();
        request.disconnect();

        // Drill down to the desired piece of data    
        JsonObject dataset = obj.getJsonObject("dataset");
        JsonArray data = dataset.getJsonArray("data");
        Object currentData = data.get(0);

        System.out.println(currentData);

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

    return baseRate;            
}

I think that you need to go down another level of array to access the value you required.

    JsonArray data = dataset.getJsonArray("data");
    JsonArray firstPieceOfData = data.get(0);
    Object firstRate = firstPieceOfData.get(1); 

If you use Jackson for reading your JSON you can use the .at() method which allows you to access the node's value via a JSON Pointer Expression which in your case would be "/dataset/data/0/1"

I've truncated your json for the purpose of this demo:

String jsonString = "{\"dataset\":{\"id\":4644596,\"dataset_code\":\"30US\",\"database_code\":\"FMAC\",\"name\":\"30-Year Fixed Rate Mortgage Average in the United States\",\"description\":\"Units: Percent\\u003cbr\\u003e\\u003cbr\\u003eNot Seasonally Adjusted\",\"refreshed_at\":\"2017-12-18T04:09:32.892Z\",\"newest_available_date\":\"2017-12-14\",\"oldest_available_date\":\"1971-04-02\",\"column_names\":[\"Date\",\"Value\"],\"frequency\":\"weekly\",\"type\":\"Time Series\",\"premium\":false,\"limit\":null,\"transform\":null,\"column_index\":null,\"start_date\":\"1971-04-02\",\"end_date\":\"2017-12-14\",\"data\":[[\"2017-12-14\",3.93],[\"2017-12-07\",3.94],[\"2017-11-30\",3.9]],\"collapse\":null,\"order\":null,\"database_id\":582}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNodes = mapper.createObjectNode();
try {
    jsonNodes = mapper.readTree(jsonString);
} catch (IOException e) {
    //e.printStackTrace();
}
System.out.println(jsonNodes.at("/dataset/data/0/1").asDouble());// 3.93

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM