我正在尝试创建一个 java 类,其中包含来自 JSON 的响应,如下所示:
{
"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%"
}
}
到目前为止,我已经尝试使用两个单独的类,其中一个类包含大量 String 和 double 对象,我最近接触到了这个:
class VantageResponse { public Map<String, Object> globalQuote; }
我一直在使用谷歌的 GSON.fromJson 将响应解析为 VantageResponse 类的对象,但它始终返回 null。我做错了什么?
protected convertToMap(JSONObject response){
JSONObject contentsOfResponse = response.getJSONObject("Global Quote");
// you will obtain the contents of the global quote
Map<String,Object> globalQuote = new HashMap<>();
Iterator<String> keys = contentsOfResponse.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = contentsOfResponse.get(key);
// Put the key-value pair into the HashMap
globalQuote.put(key, value);
}
//you can also store this as a global variable using
//this.globalQuote; (in a class)
return globalQuote;
}
开始编写一个具有 hashmap 全局变量的类,然后在包含响应的位置调用此方法。到目前为止我已经明白这应该有效。您可以评论此答案以获得其他答案。