看起来您是在正确的道路上,但是您的VantageResponse类的 struct 可能有问题.以下是一个应该可以工作的修改版本:
import com.google.gson.annotations.SerializedName;
import java.util.Map;
public class VantageResponse {
@SerializedName("Global Quote")
private GlobalQuote globalQuote;
public GlobalQuote getGlobalQuote() {
return globalQuote;
}
public void setGlobalQuote(GlobalQuote globalQuote) {
this.globalQuote = globalQuote;
}
public static class GlobalQuote {
@SerializedName("01. symbol")
private String symbol;
@SerializedName("02. open")
private double open;
@SerializedName("03. high")
private double high;
@SerializedName("04. low")
private double low;
@SerializedName("05. price")
private double price;
@SerializedName("06. volume")
private long volume;
@SerializedName("07. latest trading day")
private String latestTradingDay;
@SerializedName("08. previous close")
private double previousClose;
@SerializedName("09. change")
private double change;
@SerializedName("10. change percent")
private String changePercent;
// Getters and setters for all the fields
// You can generate these using your IDE or write them manually
// For simplicity, I'm showing just one getter here
public String getSymbol() {
return symbol;
}
public double getOpen() {
return open;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
}
}
使用此 struct ,您可以使用gson来反序列化JSON响应:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String jsonResponse = "{ \"Global Quote\": { \"01. symbol\": \"IBM\", \"02. open\": \"160.0000\", \"03. high\": \"162.0400\", \"04. low\": \"160.0000\", \"05. price\": \"161.9600\", \"06. volume\": \"4561342\", \"07. latest trading day\": \"2023-12-08\", \"08. previous close\": \"160.2200\", \"09. change\": \"1.7400\", \"10. change percent\": \"1.0860%\" } }";
Gson gson = new Gson();
VantageResponse vantageResponse = gson.fromJson(jsonResponse, VantageResponse.class);
if (vantageResponse != null && vantageResponse.getGlobalQuote() != null) {
System.out.println("Symbol: " + vantageResponse.getGlobalQuote().getSymbol());
System.out.println("Open: " + vantageResponse.getGlobalQuote().getOpen());
// Add more fields as needed
} else {
System.out.println("Failed to parse JSON response");
}
}
}