gpt4 book ai didi

java - 我怎样才能解析这个 JSON 并且不出现异常?

转载 作者:行者123 更新时间:2023-12-02 00:41:24 25 4
gpt4 key购买 nike

我有以下 JSON:

    [
{
"outcome": "Success",
"message": "",
"identity": "",
"delay": "0",
"symbol": "AAPL",
"companyname": "Apple Inc.",
"date": "Jun 08",
"time": " 4:52 PM EDT",
"open": "330.88",
"close": "332",
"previousclose": "332.04",
"high": "334.8",
"low": "330.51",
"last": "332",
"change": "-0.04",
"percentchange": "-0.012",
"volume": "1239421",
"created_at": "1307581193"
},
{
"outcome": "Success",
"message": "",
"identity": "",
"delay": "0",
"symbol": "GOOG",
"companyname": "Google Inc.",
"date": "Jun 08",
"time": " 3:59 PM EDT",
"open": "516.76",
"close": "519.28",
"previousclose": "519.03",
"high": "521.14",
"low": "515.79",
"last": "519.28",
"change": "0.25",
"percentchange": "0.048",
"volume": "229886",
"created_at": "1307576900"
}
]

这是我的 Java:

JSONArray jquotes = new JSONArray(json.toString());
if (jquotes.length() > 0) {
for (int i = 0; i < jquotes.length(); i++) {

JSONObject quote = jquotes.getJSONObject(i);

Quote myQuote = new Quote();
myQuote.setName(quote.getString("companyname"));
myQuote.setSymbol(quote.getString("symbol"));
myQuote.setLastTradePriceOnly(quote.getString("last"));
myQuote.setChange(quote.getString("change"));
myQuote.setPercentChange(quote.getString("percentchange"));

quotesAdapter.add(myQuote);
}
}

我遇到异常:

value of type org.json.JSONArray cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:107)

最佳答案

你拥有的实际上是一个 JSONArray (注意开头的括号),所以:

JSONArray array = new JSONArray (jsonString);
JSONObject obj = array.getJSONObject(0);
String outcome = obj.getString("outcome");
int delay = getInt("delay");
// etc.

API 相当简单。详情可阅读here .

关于java - 我怎样才能解析这个 JSON 并且不出现异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com