2010-09-28 95 views
0

所以我有一個JSONObject(或字符串..),看起來像這樣:在Java中重新解析JSON對象?

{"locations":[{"GeocodeResponse":{"result":{"formatted_address":"Tchibanga (TCH), Gabon","address_component":[{"long_name":"Tchibanga","type": 
["airport","establishment","transit_station"],"short_name":"Tchibanga"},{"long_name":"Mougoutsi","type": 
["administrative_area_level_2","political"],"short_name":"Mougoutsi"},{"long_name":"Nyanga","type": 
["administrative_area_level_1","political"],"short_name":"Nyanga"},{"long_name":"Gabon","type": 
["country","political"],"short_name":"GA"}],"type":["airport","establishment","transit_station"],"geometry": 
{"viewport":{"southwest":{"lng":"10.9968524","lat":"-2.8198146"},"northeast":{"lng":"11.0031476","lat":"-2.8135194"}},"location_type":"APPROXIMATE","location":{"lng":"11","lat":"-2.816667"}}},"status":"OK"}}]} 

這不過了太多的信息,我只想說

{"locations":[{"id":"Tchibanga(TCH)","parentId":"TCH","airport":"Tchibanga","category":"Airport","location":{"longitude":"11","latitude":"-2.816667"},"name":"Nyanga","country":"GA"}]} 

我怎麼會去到正確解析這個?

編輯:不,我不想讓另一個庫來解析它。

+1

你看過使用json.org的JSON庫嗎? – 2010-09-28 12:51:18

+0

TMI,以什麼方式?你想過濾掉東西,重寫JSON還是其他的東西?是的,你確實需要另一個lib,而不是來自org.json的概念驗證。即使你還不知道你需要它:) – StaxMan 2010-09-29 04:00:50

回答

1

您需要從here獲得JSON庫(您將必須編譯源代碼並確保類位於類路徑中)並創建一個JSONObject

A JSONObject只是一個包含更多地圖,數組和對象的地圖。它很容易(但繁瑣)的解析,因爲有這麼多的嵌套。我們來看看如何解析第一個long_name的值。如果您查看JSON源字符串,您將看到long_name的位置在locations/GeocodeResponse/result/address_component中。所以,你會做這樣的事情:

//create a jsonObject 
JSONObject jsonObject = new JSONObject("{ \"locations\" ...<snipped>... ] }"); 

//run some getters until you get to the address_component 
JSONArray locations = (JSONArray)jsonObject.get("locations"); 
JSONObject location = (JSONObject)locations.get(0); // get the first location 
JSONObject geoCodeResponse = (JSONObject)location.get("GeocodeResponse"); 
JSONObject result = (JSONObject)geoCodeResponse.get("result"); 
JSONArray addressArray = (JSONArray)result.get("address_component"); 

//print out the long_name from the address 
JSONObject address = (JSONObject)addressArray.get(0); 
String longName = (String)address.get("long_name"); 
System.out.println(longName); //prints Tchibanga 

不過,我會建議以使用JsonPath,讓您的生活輕鬆了許多。

一旦你挑選出你需要的元素,你就可以構建所需的輸出JSONObject

+0

現在我看到了結構,這解決了我的問題。謝謝! – Mantar 2010-09-28 13:35:30

+0

有一個在線的JSON格式化程序(http://jsonformat.com/),它將更清晰地向您顯示您的結構。 – dogbane 2010-09-28 13:37:26

1

看來,你想要的只是將一個JSON塊轉換爲一個不同的塊。也許這個問題會幫助你:XSLT equivalent for JSON