1

我从谷歌地图 Api 开始。按照互联网上的一些示例。我想出了这些代码。我可以通过创建 HttpURLCONnection 很容易地获取 Json 代码,但不知何故我遇到了运行时错误。不知何故我无法创建 Json 对象。我搜索了很多,但没有找到 JSONObject 和 Runtimeerror 之间的任何关系

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;

public class Parser {

    public static void main(String args[])
    {
        String response="";
        int lat1=20270000,lon1=85520000,lat2=20264500,lon2=85835500;
        String urlString="https://maps.googleapis.com/maps/api/directions/json?origin="+Double.toString((double)lat1/1E6)+","+Double.toString((double) lon1/1E6)+"&destination="+Double.toString((double)lat2/1E6)+","+Double.toString((double) lon2/1E6)+"&sensor=true";
        HttpURLConnection urlConnection= null;
            URL url = null;
            try{
            url = new URL(urlString.toString());
            urlConnection=(HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.connect();
            InputStream inStream = urlConnection.getInputStream();
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
            String temp;
            while((temp = bReader.readLine()) != null){
                response += temp;
            }
            System.out.println(response);
            bReader.close();
            inStream.close();
            urlConnection.disconnect();
            }
            catch(Exception e){}

            ArrayList<Bundle> list = new ArrayList<Bundle>();
            try {
                System.out.println(response.toString()); // uptil here every thing is fine..... I am getting correct Json text.
                JSONObject jsonObject = new JSONObject(response);  //I am getting a runtime error in this line. Can't figure out the reason
                System.out.println(jsonObject);
                JSONArray routesArray= jsonObject.getJSONArray("routes");

                JSONObject route = routesArray.getJSONObject(0);
                JSONArray legs = route.getJSONArray("legs");
                JSONObject leg = legs.getJSONObject(0);

                JSONObject durationObject = leg.getJSONObject("duration");
                String duration = durationObject.getString("text");
                System.out.println("egferg"+duration);

            }
            catch(Exception e1){e1.printStackTrace();}


    }


}
4

0 回答 0