上次後端經過模擬http請求百度地圖接口,獲得的是一個json字符串,而我只須要其中的某個key對應的value。html
當時我是經過截取字符串取的,後來以爲不太合理,今天整理出了兩種處理解析json字符串的方式。java
供你們參考。json
順便說一下所解析的字符串必定要是「{」開始,「}」結束,後端
而百度地圖返回數據是這樣的app
renderReverse&&renderReverse({"status":0,"result":{"location":{"lng":116.23412299999993,"lat":40.234523047443769},"formatted_address":"北京市昌平區北環路54號樓","business":"昌平縣城","addressComponent":{"country":"中國","country_code":0,"country_code_iso":"CHN","country_code_iso2":"CN","province":"北京市","city":"北京市","city_level":2,"district":"昌平區","town":"","adcode":"110114","street":"北環路","street_number":"54號樓","direction":"附近","distance":"27"},"pois":[],"roads":[],"poiRegions":[{"direction_desc":"內","name":"北環裏小區","tag":"房地產;住宅區","uid":"dc0f0adc0773a420f8221312"}],"sematic_description":"北環裏小區內,雙海包裝製品廠北299米","cityCode":131}})
因此在解析前我加了這行代碼ui
String subData = dataStr.substring(dataStr.indexOf("(") + 1, dataStr.lastIndexOf(")"));
這裏以2.4version爲例spa
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>${jackson.version}</version>
</dependency>
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
if("" != dataStr){
ObjectMapper objectMapper = new ObjectMapper();
String subData = dataStr.substring(dataStr.indexOf("(") + 1, dataStr.lastIndexOf(")"));
JsonNode jsonNode = objectMapper.readTree(subData);
adcode = jsonNode.get("result").get("addressComponent").get("adcode").toString().replace("\"","");
}
最後獲得須要的經緯度信息hibernate
這裏以2.4version爲例code
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
import net.sf.json.JSONObject;
import net.sf.json.JSON;
String subData = dataStr.substring(dataStr.indexOf("(") + 1, dataStr.lastIndexOf(")"));
JSONObject jsonData = JSONObject.fromObject(subData);
JSONObject result = (JSONObject) jsonData.get("result"); JSONObject location = (JSONObject) result.get("location"); if(null != location.get("lng") && null != location.get("lat")){ String lng = location.get("lng").toString(); String lat = location.get("lat").toString(); doubles[0] = Double.parseDouble(lng); doubles[1] = Double.parseDouble(lat); }
最後獲得須要的經緯度信息orm