簡單說一下背景
上次后端通過模擬http請求百度地圖接口,得到的是一個json字符串,而我只需要其中的某個key對應的value。
當時我是通過截取字符串取的,后來覺得不太合理,今天整理出了兩種處理解析json字符串的方式。
供大家參考。
順便說一下所解析的字符串一定要是“{”開始,“}”結束,
而百度地圖返回數據是這樣的
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}})
所以在解析前我加了這行代碼
String subData = dataStr.substring(dataStr.indexOf("(") + 1, dataStr.lastIndexOf(")"));
第一種(ObjectMapper)
首先在pom文件配置需要的jar
這里以2.4version為例
<!-- 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>
其次在java類中引入需要的外部類
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
最后處理百度地圖返回的json串
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("\"","");
}
最后得到需要的經緯度信息
第二種(JSONObject)
首先在pom文件配置需要的jar
這里以2.4version為例
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
其次在java類中引入需要的外部類
import net.sf.json.JSONObject;
import net.sf.json.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); }
最后得到需要的經緯度信息