JSONException类型与JSONArray不匹配JsonString

时间:2014-05-25 17:00:45

标签: android google-maps latitude-longitude

我试图从我的数据库下载纬度和经度数据,并在android中为它们创建地图标记。 但是我收到错误

05-25 18:54:33.834: E/ExampleApp(4893): Error processing JSON
05-25 18:54:33.834: E/ExampleApp(4893): org.json.JSONException: Value 51.9111546,4.477839 at latlng of type java.lang.String cannot be converted to JSONArray
05-25 18:54:33.834: E/ExampleApp(4893):     at org.json.JSON.typeMismatch(JSON.java:100)
05-25 18:54:33.834: E/ExampleApp(4893):     at org.json.JSONObject.getJSONArray(JSONObject.java:553)
05-25 18:54:33.834: E/ExampleApp(4893):     at info.androidhive.jsonparsen.mapview.createMarkersFromJson(mapview.java:117)
05-25 18:54:33.834: E/ExampleApp(4893):     at info.androidhive.jsonparsen.mapview$2.run(mapview.java:99)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.os.Handler.handleCallback(Handler.java:733)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.os.Handler.dispatchMessage(Handler.java:95)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.os.Looper.loop(Looper.java:136)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.app.ActivityThread.main(ActivityThread.java:5103)
05-25 18:54:33.834: E/ExampleApp(4893):     at java.lang.reflect.Method.invokeNative(Native Method)
05-25 18:54:33.834: E/ExampleApp(4893):     at java.lang.reflect.Method.invoke(Method.java:515)
05-25 18:54:33.834: E/ExampleApp(4893):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
05-25 18:54:33.834: E/ExampleApp(4893):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
05-25 18:54:33.834: E/ExampleApp(4893):     at dalvik.system.NativeStart.main(Native Method)

我似乎无法找到如何解决此问题

这是我的活动代码(除了一些SetUpMap方法)。

protected void retrieveAndAddCities() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {
        // Connect to the web service
        URL url = new URL(SERVICE_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createMarkersFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}

void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArray.getJSONObject(i);
        map.addMarker(new MarkerOptions()
            .title(jsonObj.getString("name"))
            .snippet(Integer.toString(jsonObj.getInt("population")))
            .position(new LatLng(
                    jsonObj.getJSONArray("latlng").getDouble(0),
                    jsonObj.getJSONArray("latlng").getDouble(1)
             ))
        );
    }
}
}

JSON回应

[{"name":"AlbertHeijn","latlng":"51.9111546,4.477839","population":"1234"},{"name":"Jumbo","latlng":"51.9054127,4.4960587","population":"23"}]

我正在使用json_encode($resultarray)在网站上显示我的JSON。

任何详细的解释都将不胜感激。

3 个答案:

答案 0 :(得分:0)

对应于&#34; latlng&#34;的值在您的JSON中是一个字符串而不是一个数组。因此jsonObj.getJSONArray("latlng")无法工作。

我看到了两个问题的解决方案:

  • 您使用jsonObj.getString("latlng")提取字符串,将其拆分为逗号,然后转换为两个值的两倍。

    JSONObject jsonObj = jsonArray.getJSONObject(i);
    string s = jsonObj.getString("latlng"); // "51.9111546,4.477839";
    string[] lat_long = s.Split(',');
    map.addMarker(new MarkerOptions()
            .title(jsonObj.getString("name"))
            .snippet(Integer.toString(jsonObj.getInt("population")))
            .position(new LatLong(
                    Convert.ToDouble(lat_long[0]),
                    Convert.ToDouble(lat_long[1])))
            );
    
  • 您修改JSON以包含&#34; latlong&#34;的数组。值并提取它(代码低于JSON)

[
    {
        "name": "AlbertHeijn",
        "latlng": {
            "lat": "51.9111546",
            "long": "4.477839"
        },
        "population": "1234"
    },
    {
        "name": "Jumbo",
        "latlng": {
            "lat": "51.9054127",
            "long": "4.4960587"
        },
        "population": "23"
    }
]

代码:

JSONObject location = object.getJSONObject("latlng");
[...]
.position(new LatLng(
                   location.getString("lng"),
                   location.getString("lat")
             ))

关于最后一点,我使用了location.getString(),因为您的原始JSON是使用纬度和经度值的字符串构建的......要使用getDouble(),您应该删除这些值周围的引号,即:< / p>

 "latlng": {
                "lat": 51.9054127,
                "long": 4.4960587
            },

答案 1 :(得分:0)

How to decode JSON values in my Android Aplication?

上查看我的答案

这会对你有所帮助。您可能想要使用FORCE_OBJECT或json_encode(“data”,$ yourarray)

答案 2 :(得分:0)

获取lat
getString

然后使用split by delimiter并提取lat和long的值并将其存储在两个变量中并使用它们。