首页 > 解决方案 > 带有GSON和多个元素的Java中的HttpRequest

问题描述

我正在尝试在 Java 中获取 JSON HttpRequest 的“符号”。我想使用谷歌的 GSON,但是我无法达到任何值......我的对象中总是有一个空值......我知道错误是“stock.symbol”我当然需要放一些“节点”之前......我迷路了......所以......

这里的代码:

HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://yahoo-finance-low-latency.p.rapidapi.com/v6/finance/quote?symbols=AAPL&lang=en&region=CA"))
            .header("x-rapidapi-key", "---")
            .header("x-rapidapi-host", "***")
            .method("GET", HttpRequest.BodyPublishers.noBody())
            .build();

    try {
        HttpResponse<String> reponse = null;
        reponse = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.print(reponse.body());

        Gson gson = new Gson();

        Stock stock = gson.fromJson(reponse.body(), Stock.class);
        System.out.println("******************************************************");
        System.out.println(stock.symbol + stock.displayName + stock.quoteType);
        System.out.println("******************************************************");


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

}

这是我的输出,您将能够以 JSON 格式从 api 中看到答案:

{"quoteResponse":{"result":[{"language":"en-US","region":"CA","quoteType":"EQUITY","quoteSourceName":"Nasdaq Real Time Price","triggerable":true,"currency":"USD","firstTradeDateMilliseconds":345479400000,"priceHint":2,"postMarketChangePercent":-0.0956731,"postMarketTime":1621641596,"postMarketPrice":125.31,"postMarketChange":-0.120003,"regularMarketChange":-1.8799973,"regularMarketChangePercent":-1.4767083,"regularMarketTime":1621627203,"averageAnalystRating":"2.0 - Buy","tradeable":false,"esgPopulated":false,"marketState":"POSTPOST","regularMarketPrice":125.43,"regularMarketDayHigh":128.0,"regularMarketDayRange":"125.21 - 128.0","regularMarketDayLow":125.21,"regularMarketVolume":79152773,"regularMarketPreviousClose":127.31,"bid":125.37,"ask":125.37,"bidSize":12,"askSize":10,"fullExchangeName":"NasdaqGS","financialCurrency":"USD","regularMarketOpen":127.82,"averageDailyVolume3Month":103188411,"averageDailyVolume10Day":86685085,"fiftyTwoWeekLowChange":47.1575,"fiftyTwoWeekLowChangePercent":0.60247856,"fiftyTwoWeekRange":"78.2725 - 145.09","fiftyTwoWeekHighChange":-19.659996,"fiftyTwoWeekHighChangePercent":-0.13550209,"fiftyTwoWeekLow":78.2725,"fiftyTwoWeekHigh":145.09,"dividendDate":1620864000,"earningsTimestamp":1619627400,"earningsTimestampStart":1627469940,"earningsTimestampEnd":1627905600,"trailingAnnualDividendRate":0.82,"trailingPE":28.192854,"trailingAnnualDividendYield":0.006440971,"epsTrailingTwelveMonths":4.449,"epsForward":5.36,"epsCurrentYear":5.2,"priceEpsCurrentYear":24.121155,"sharesOutstanding":16687599616,"bookValue":4.146,"fiftyDayAverage":130.1347,"fiftyDayAverageChange":-4.7047043,"fiftyDayAverageChangePercent":-0.03615257,"twoHundredDayAverage":127.04788,"twoHundredDayAverageChange":-1.6178818,"twoHundredDayAverageChangePercent":-0.012734425,"marketCap":2093125599232,"forwardPE":23.40112,"priceToBook":30.253258,"sourceInterval":15,"exchangeDataDelayedBy":0,"exchange":"NMS","shortName":"Apple Inc.","longName":"Apple Inc.","messageBoardId":"finmb_24937","exchangeTimezoneName":"America/New_York","exchangeTimezoneShortName":"EDT","gmtOffSetMilliseconds":-14400000,"market":"us_market","displayName":"Apple","symbol":"AAPL"}],"error":null}}******************************************************

空空空`


进程以退出代码 0 结束

 public class Stock {
public String symbol, displayName, quoteType;}

标签: javajsongsonhttprequest

解决方案


我们需要获取结果数组中的 JSON:

Gson gson = new Gson();

 JsonObject json = gson.fromJson(jsonStr, JsonObject.class)
        .get("quoteResponse")
        .getAsJsonObject()
        .get("result")
        .getAsJsonArray()
        .get(0) // only one object in the array
        .getAsJsonObject();

String symbol = json.get("symbol").getAsString();
String displayName = json.get("displayName").getAsString();
String quoteType = json.get("quoteType").getAsString();

Stock stock = new Stock(symbol, displayName, quoteType);

推荐阅读