我在使用 JSON 方面确实是个新手,但我的 Web 服务有问题。使用普通的 JSON 对象我没有问题。我想从 Web 服务中获取两个数组(字符串和整数),所以我尝试将它们放入两个 JSON 数组中,并将这两个放入一个 JSON 对象中。现在我希望他们进入我的 Android 应用程序,但我只是遇到错误。
public static String constructJSON(Integer[] array, String[] array2) {
JSONObject mainObj = new JSONObject();
try {
JSONObject firstArray = new JSONObject();
firstArray.put("array0", array[0]);
firstArray.put("array1", array[1]);
firstArray.put("array2", array[2]);
firstArray.put("array3", array[3]);
firstArray.put("array4", array[4]);
JSONObject secondArray = new JSONObject();
secondArray.put("sArray0", array2[0]);
secondArray.put("sArray1", array2[1]);
secondArray.put("sArray2", array2[2]);
secondArray.put("sArray3", array2[3]);
secondArray.put("sArray4", array2[4]);
JSONArray JArr = new JSONArray();
JArr.put(firstArray);
JArr.put(secondArray);
mainObj.put("arrays", JArr);
} catch (JSONException e) {
}
return mainObj.toString();
}
现在是 Android Studio 中的方法:
private void getBW(String krankheit) {
RequestParams params = new RequestParams();
params.put("krankheit", krankheit);
// Invoke RESTful Web Service with Http parameters
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
try {
// JSON Object
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("array1");
JSONArray secondJsonArr= obj.getJSONArray("array2");
for (int k = 0; k < 5; k++) {
Bewertung1[k] = (Integer) firstJsonArr.get(k);
}
for (int j = 0; j < 5; j++) {
medikament[j] = (String) secondJsonArr.get(j);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
我尝试了不同的解决方案,但没有一个对我有用。我希望你们能帮助我。
最佳答案
我建议您使用 gson安卓库。它提供了简单的函数来解析 json 对象。 看看这个图书馆:https://github.com/google/gson
关于java - 接收带有 2 个数组的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44909273/