簡體   English   中英

無法解析復雜的json

[英]Trouble parsing through complicated json

我有一個看起來像這樣的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

但是它看起來好像沒有嘗試catch,因為它在日志中打印下一行:

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

該錯誤告訴您no value for JSON 這是因為這一行:

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

基本上,在從JSON對象中選擇屬性時,需要使用propery鍵。 看起來你想用來獲取你的天氣項目的關鍵是“數據”,這將是一個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
}

此行將引發錯誤,因為您的JSON沒有名為“JSON”的屬性:

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

除此之外,看到你想要達到的目標是非常困惑的。 我還建議使用elf_zwölf發布的Gson。

雖然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 Objects基本上只是大型嵌套數組和鍵值對。 如果是JSONObject,則傳遞給get方法的參數是關鍵字; 如果是JSONArray,則傳入索引! 使用類型化的getMethods和鏈接,我在這里演示也有助於清理代碼很多!

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM