gpt4 book ai didi

java - 无法解析复杂的 json

转载 作者:太空狗 更新时间:2023-10-29 15:54:12 30 4
gpt4 key购买 nike

我有一个如下所示的 json 结构:

http://pastebin.com/d6Dc1Fj9

我的 json 解析看起来像这样,根据教程编辑,所以它有点脏,但一旦我弄清楚它是如何工作的,我会清理它。当一个 json 对象包含一组更多 json 对象时,我在解析 json 时有点迷茫。

private class ReadJSONResult extends AsyncTask
<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}

protected void onPostExecute(String result) {
try {
Log.d("asycTask", "[ Gets into asyc task ]");
///get
Log.d("search", "[ check if we get search results ]");
Log.d("search", "[" + result + "]");

JSONObject jsonObject = new JSONObject(result);
JSONObject weatherObservationItems =
new JSONObject(jsonObject.getString("JSON"));

Toast.makeText(getBaseContext(),
weatherObservationItems.getString("totalResults"),
Toast.LENGTH_SHORT).show();


} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}

//gets the json from the inputed url
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}

我知道我得到了 json 结果,因为从我的日志中它打印了结果变量,我确实得到了我的 json。

更新:

查看我的日志让我更加困惑。当我打印结果变量时,我得到了这个

06-13 14:56:00.533: D/asycTask(19191): [ Gets into asyc task ]
06-13 14:56:00.533: D/search(19191): [ check if we get search results ]
06-13 14:56:00.541: D/search(19191): [{"currentPage":1,"numberOfPages":1,"totalResults":8,"data":[{"id":"YAKFea","name":"90 Shilling","description":"We introduced 90 Shilling, our flagship beer, at our opening party in 1989. For a while, we\u2019d been wondering what would happen if we lightened up the traditional Scottish ale? The result is an irresistibly smooth and delicious medium-bodied amber ale. The name 90 Shilling comes from the Scottish method of taxing beer. Only the highest quality beers were taxed 90 Shillings. A shilling was a British coin used from 1549 to 1982. We think you\u2019ll find this original ale brilliantly refreshing, and worth every shilling.","abv":"5.3","ibu":"27","glasswareId":4,"availableId":1,"styleId":9,"isOrganic":"N","labels":{"icon":"http:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/YAKFea\/upload_1CxY2l-icon.png","medium":"http:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/YAKFea\/upload_1CxY2l-medium.png","large":"http:\/\/s3.amazonaws.com\/brewerydbapi\/beer\/YAKFea\/upload_1CxY2l-large.png"},"status":"verified","statusDisplay":"Verified","createDate":"2012-01-03 02:42:38","updateDate":"2012-03-22 13:04:31","glass":{"id":4,"name":"Pilsner","createDate":"2012-01-03 02:41:33"},"available":{"id":"1","name":"Year Round","description":"Available year round as a staple beer."},"style":{"id":9,"categoryId":1,"category":{"id":1,"name":"British Origin Ales","createDate":"2012-03-21 20:06:45"},"name":"Scottish-Style Export Ale","description":"The overriding character of Scottish export ale is sweet, caramel-like, and malty. Its bitterness is perceived as low to medium. Hop flavor or aroma should not be perceived. It has medium body. Fruity-ester character may be apparent. Yeast characters such as diacetyl (butterscotch) and sulfuriness are acceptable at very low levels. The color will range from golden amber to deep brown. Bottled versions of this traditional draft beer may contain higher amounts of carbon dioxide than is typical for mildly carbonated draft versions. Chill haze is acceptable at low temperatures. Though there is little evidence suggesting that traditionally made Scottish-style export ales exhibited peat smoke character, the current marketplace offers many Scottish-style export ales with peat or smoke character present at low to medium levels. Thus a peaty\/smoky character may be evident at low to medium levels (ales with medium-high or higher smoke character would be considered a smoke flavored beer and considered in another category). Scottish-style export ales may be split into two subcategories: Traditional (no smoke character) and Peated (low level of peat smoke character).","ibuMin":"15","ibuMax":"25","abvMin":"4","abvMax":"5.3","srmMin":"10","srmMax":"19","ogMin":"1.04","fgMin":"1.01","fgMax":"1.018","createDate":"2012-03-21 20:06:45"},"breweries":[{"id":"rQkKIB","name":"Odell Brewing Company","description":"We love beer. We talk about beer. We dream about beer. And we make incredible beer. We don't mess around with serving food, making music or cutting up limes to mask our beer's flavor. Our dreams lead us to create imaginative, big, bold and beautiful beers. Every ounce of our passion is poured directly into the next bottle you open. Our mission is simple; to make consistently great beer.\r\n\r\nHandcrafted classics and small batch experimental beers that include Pale Ales, Stouts, Pilsners and Porters. Come visit us in our tap room for a taste of how we keep the craft in craft beer.","website":"http:\/\/odellbrewing.com\/","established":"1989","isOrganic":"N","images":{"icon":"http:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/rQkKIB\/upload_DXbWkA-icon.png","medium":"http:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/rQkKIB\/upload_DXbWkA-medium.png","large":"http:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/rQkKIB\/upload_DXbWkA-large.png"},"status":"verified","statusDisplay":"Verified","createDate":"2012-01-03 02:42:04","updateDate":"2012-03-27 01:06:32","locations":[{"id":"Q4eTmd","name":"Main Brewery","streetAddress":"800 East Lincoln Avenue","locality":"Fort Collins","region":"C

但是它看起来像 try catch 失败了,因为它在日志的下一行打印了这一行:

06-13 14:56:00.580: D/ReadWeatherJSONFeedTask(19191): No value for JSON

最佳答案

错误告诉您 JSON 没有值。这是因为这一行:

JSONObject weatherObservationItems = new JSONObject(jsonObject.getString("JSON"));

基本上,从 JSON 对象中选择属性时需要使用属性键。看起来您想用来获取天气项目的键是“数据”,它将是一个 JSONArray。您可以改为创建它,例如:

JSONArray weatherObservationItems = jsonObject.getJSONArray("data");

然后您可以遍历 JSONArray查看您尝试查询的 totalResults 属性。

要遍历数组中的时间,只需遍历它并拉出每个 JSONObject。例如:

for(int i = 0; i < weatherObservationItems.length(); i++) {
JSONObject item = weatherObservationItems.getJSONIbject(i);
String name = item.getString("name");
String desc = item.getString("description");
// etc etc
}

关于java - 无法解析复杂的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088766/

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