java - 从Java中的谷歌地图API解析Json数组

标签 java json api parsing location

我得到这个json数组https://maps.googleapis.com/maps/api/geocode/json?address=10115,germany来自 Google map API。现在我想用Java解析它并从“location”部分获取“lat”和“lng”,但我不知道如何获取它。

最佳答案

这是代码-

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"));


        }
    }

输出-

Lat = 52.532614
Lng = 13.3777035

关于java - 从Java中的谷歌地图API解析Json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25360231/

相关文章:

facebook - 图谱 API/搜索端点中的 &fields 参数可以使用哪些字段?

python - 我想使用 TOTP 将我的响应发送到 API?

java - Wait()/notify() 同步

json - Ansible : pass a variable in a json_query filter

java - 要么显示最大小数位数,要么根本不显示

python - 删除对象数组中的 JSON 属性

android - 如果数据已经加载,则停止从 .json 加载数据

ruby-on-rails - rake 路由上未初始化的常量 API

java - 从多平面对象到层次结构对象的 ModelMapper 映射

Java JDBC 多重插入和一般最佳实践