2

我有一个看起来像这样的 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 结果,因为从我的日志中它打印了 results 变量并且我确实得到了我的 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
4

3 回答 3

4

错误告诉你有no value for 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
}
于 2013-06-13T14:01:27.463 回答
2

此行将引发错误,因为您的 JSON 没有名为“JSON”的属性:

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

除此之外,看到您想要实现的目标非常令人困惑。我还建议使用 elf_zwölf 发布的 Gson。

于 2013-06-13T14:02:29.917 回答
2

虽然 Gson 是一个很好的库,但您实际上并不需要它。Android 自带了 org.json 库!!对于初学者,如果您只是学习 JSON 解析,这里的文档将是一个非常有用的参考工具。

通常,像之前发布的教程中演示的那样创建模型可能会很繁重,而且工作量太大。使用 org.json 库,您可以将 get 方法链接在一起,如下所示:

JSONObject json = new JSONObject(what you put in pastebin);
String string = json.getJSONArray('data')
                    .getJSONObject(0)
                    .getString("name");

并以这种方式遍历 json。Json 对象基本上只是大的嵌套数组集和键值对。如果是JSONObject,你传递给get方法的参数就是key;如果是 JSONArray,则传入索引!正如我在这里演示的那样,使用类型化的 getMethods 和链接也有助于清理代码!

希望能帮助到你!

于 2013-06-13T14:05:09.993 回答