gpt4 book ai didi

java - 如何使用java在android studio中解析这个JSON字符串

转载 作者:行者123 更新时间:2023-12-01 21:57:03 25 4
gpt4 key购买 nike

这是我遇到的错误!

exception caught:
org.json.JSONException: Value com.squareup.okhttp.internal.http.RealResponseBody@42b1af18 of type java.lang.String cannot be converted to JSONObject

主要 Activity

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();

关于java - 如何使用java在android studio中解析这个JSON字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34128249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com