android - JSON格式错误

标签 android

我想传递地址并想要纬度和经度。但我从maps.google.com 获得了完整的字符串。但是JSON格式有错误。

我尝试下面的代码

Error :Couldn't get connection factory client

getLocationInfo("3 cité Nollez 巴黎法国");

public static void getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }

            System.out.print(stringBuilder);
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {

            jsonObject = new JSONObject(stringBuilder.toString());

            longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");

                System.out.print(longitute);


                latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

                System.out.print(latitude);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      //  return jsonObject;
    }

日志记录

{
   "results" : [
      {
         "address_components" : [
            {
                "long_name" : "3",
                "short_name" : "3",
                "types" : [ "street_number" ]
             },
             {
                "long_name" : "Cité Nollez",
                "short_name" : "Cité Nollez",
                "types" : [ "route" ]
             },
             {
                "long_name" : "18th arrondissement of Paris",
                "short_name" : "18th arrondissement of Paris",
                "types" : [ "sublocality", "political" ]
             },
             {
                "long_name" : "Paris",
                "short_name" : "Paris",
               "types" : [ "locality", "political" ]
             },
             {
              "long_name" : "Paris",
                "short_name" : "75",
                "types" : [ "administrative_area_level_2", "political" ]
             },
             {
                "long_name" : "Ã?le-de-France",
                "short_name" : "IdF",
                "types" : [ "administrative_area_level_1", "political" ]
             },
             {
                "long_name" : "France",
                "short_name" : "FR",
               "types" : [ "country", "political" ]
            },
             {
             "long_name" : "75018",
              "short_name" : "75018",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "3 Cité Nollez, 75018 Paris, France",
         "geometry" : {
            "location" : {
               "lat" : 48.89376110,
               "lng" : 2.33742180
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 48.89511008029150,
                  "lng" : 2.338770780291502
               },
               "southwest" : {
                  "lat" : 48.89241211970850,
                  "lng" : 2.336072819708498
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}
03-14 13:51:35.776: I/MapActivity(1430): Handling network change notification:CONNECTED
03-14 13:51:35.776: E/MapActivity(1430): Couldn't get connection factory client

最佳答案

在 Map Activity 中的 super.onCreate() 之前添加以下代码

示例 Activity :-

 public class ExampleActivity extends Activity {

    // url to make request
    private static String url = "http://maps.googleapis.com/maps/api/geocode/json?address="+address.replace(" ", "%20")+"&sensor=true";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tvlat = (TextView) findViewById(R.id.tvlat);
        tvlng = (TextView) findViewById(R.id.tvlng);

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
             System.out.println("Location Latitude"
                + json.getJSONArray("results").getJSONObject(0)
                        .getJSONObject("geometry")
                        .getJSONObject("location").getString("lat"));

               System.out.println("Location Longitude"
                + json.getJSONArray("results").getJSONObject(0)
                        .getJSONObject("geometry")
                        .getJSONObject("location").getString("lng"));    
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

JSONPareser:-

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();            

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

然后运行您的应用程序,它对我来说运行良好。

关于android - JSON格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15404245/

相关文章:

android - 如何填充 RelativeLayout 中两个 View 之间的空间

java - 需要将字符串转换为我可以发送的 Intent 吗?

c# - 如何使用 Firebase 创建统一的 Facebook 登录信息?

java - 创建签名的 bundle 版本。错误 : Android resource linking failed

android - ArrayIndexOutOfBoundsException 异常

android - 防止 View 在 RelativeLayout 中重叠

java - Android Fragment 未从界面更新图像

java - 输入类型为 : textEmailAddress not able to type text using Espresso 的 EditText

android - 清除 Android picasso 图像库的磁盘/SD 卡缓存

java - Android Google Maps v2 多边形性能问题?