这个错误是什么意思?为什么它一直出现?

时间:2015-07-21 05:41:38

标签: java android

这是我的项目的MainActivity类,我试图调用具有预测信息的JSON格式链接:

public class MainActivity extends ActionBarActivity {

    public static final String TAG = MainActivity.class.getSimpleName();
    private CurrentWeather mCurrentWeather;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String apiKey = "bf092d4688e81db384b589d7a225e061";
        double apiLat = 37.8267;
        double apiLong = -122.423;
        String forecastURL = "https://api.forecast.io/forecast/" + apiKey + "/" + apiLat + "," + apiLong;
        if (isNetworkOnline()) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(forecastURL).build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String JsonData = response.body().toString();
                        Log.v(TAG, response.body().string());
                        if (response.isSuccessful()) {
                            mCurrentWeather = getCurrentDetails(JsonData);
                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException | JSONException e) {
                        Log.e(TAG, "Caught exception: ", e);
                    }
                }
            });
        } else {
            Toast.makeText(this, getString(R.string.network_not_available), Toast.LENGTH_LONG).show();
        }
        Log.d(TAG, "Main UI code is running.");
    }

    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
        // getting the first JSON object in the json formatted link.
        JSONObject forecast = new JSONObject(jsonData);
        String timeZone = forecast.getString("timezone");

        // getting the second JSON object in the json format by looking for the
        // keyword "currently"
        JSONObject currently = forecast.getJSONObject("currently");
        CurrentWeather currentWeather = new CurrentWeather();
        currentWeather.setHumidity(currently.getDouble("humidity"));
        currentWeather.setIcon(currently.getString("icon"));
        currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
        currentWeather.setSummary(currently.getString("summary"));
        currentWeather.setTemperature(currently.getDouble("temperature"));
        currentWeather.setTime(currently.getLong("time"));
        currentWeather.setTimeZone(timeZone);
        // Displaying the formatted time from seconds to the format we
        // specified.
        Toast.makeText(MainActivity.this, currentWeather.getFormattedTime(), Toast.LENGTH_LONG).show();
        return currentWeather;
    }

    private boolean isNetworkOnline() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}

但是,此错误不断出现,我不确定此错误的含义及其发生的原因。

07-21 01:37:10.644  20859-20908/com.example.android.stormy E/MainActivity﹕ Caught exception:
org.json.JSONException: Value com.squareup.okhttp.internal.http.RealResponseBody@423e87e0 of type java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:111)
        at org.json.JSONObject.<init>(JSONObject.java:158)
        at org.json.JSONObject.<init>(JSONObject.java:171)
        at com.example.android.stormy.MainActivity.getCurrentDetails(MainActivity.java:73)
        at com.example.android.stormy.MainActivity.access$100(MainActivity.java:22)
        at com.example.android.stormy.MainActivity$1.onResponse(MainActivity.java:54)
        at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:170)
        at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)

1 个答案:

答案 0 :(得分:0)

java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:111)

这可能是因为您使用的网络服务未返回jsonObject

当您发送到Web服务的密钥不正确时,或者如果密钥值与数据库中的某个主键重复,或者可能是您的Web服务导致该密钥,则可能会发生这种情况。

可能的解决方案:

确保密钥正确并与您的Web服务密钥匹配,调试并找出返回的json字符串是什么,以确定其是否重复并更改您尝试发送的值,请确保您的网络服务在将其更改为GET并通过params发送URL后会返回有效值。

或者可能是由于在撰写String时添加了不想要的字符,如果是这样的话;小鸡this