使用java解析来自GoogleMapAPI的JSON数据
我想解析从GoogleMapAPI返回的JSON数据。我尝试了以下代码使用java解析来自GoogleMapAPI的JSON数据,java,json,google-maps,parsing,Java,Json,Google Maps,Parsing,我想解析从GoogleMapAPI返回的JSON数据。我尝试了以下代码 import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.cl
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonReader {
public static void main(String[] args) throws ParseException {
InputStream inputStream = null;
String json = "";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/geocode/json?address=10115,germany");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
} catch(Exception e) {
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"),8);
StringBuilder sbuild = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sbuild.append(line);
}
inputStream.close();
json = sbuild.toString();
} catch(Exception e) {
}
//now parse
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONObject jb = (JSONObject) obj;
//now read
JSONArray jsonObject1 = (JSONArray) jb.get("results");
JSONObject jsonObject2 = (JSONObject)jsonObject1.get(0);
JSONObject jsonObject3 = (JSONObject)jsonObject2.get("geometry");
JSONObject location = (JSONObject) jsonObject3.get("location");
System.out.println( "Lat = "+location.get("lat"));
System.out.println( "Lng = "+location.get("lng"));
}
}
以上代码的来源就是这个问题的答案。
如何解决此问题???根据异常添加apache commons依赖项。如果您看到错误,它会说缺少一个类,特别是org.apache.commons.logging包中的LogFactory。在线上有大量教程介绍如何将包含此类的jar添加到类路径中。这是一个愚蠢的错误。不过谢谢你的回复。