这是我得到的错误!
exception caught:
org.json.JSONException: Value com.squareup.okhttp.internal.http.RealResponseBody@42b1af18 of type java.lang.String cannot be converted to JSONObject
主要活动
public class Main_Activity extends Activity {
public static final String TAG = Main_Activity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_);
double latitude = 37.8267;
double longitude = -122.423;
String apiKey = "26351d54df6d07aff2086c471da36d36";
String forecastURL = "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
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 {
String jsonData = response.body().toString();
Log.e(TAG, jsonData);
try {
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
} else {
alertUserAboutError();
}
}
catch (JSONException e){
Log.e(TAG, "exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_isUnavailable), Toast.LENGTH_LONG).show();
}
Log.e(TAG, "Main_Activity is running!");
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("{timezone}");
Log.i(TAG, "From json: " + timezone);
return new CurrentWeather();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
Boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment mDialog = new AlertDialogFragment();
mDialog.show(getFragmentManager(), "error_dialog");
}
}
最佳答案
一切似乎都很好。除了下面的行
String jsonData = response.body().toString();
用以下内容替换上面的行
String jsonData = response.body().string();