我在使用JSON时非常新,我的Web服务有问题。使用普通的JSON对象我没有问题。我想从Web服务(String和Integer)中获取两个Arrays,所以我试图将它们放入两个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();
}
}
});
}
我尝试了不同的解决方案,但它们都没有为我工作。我希望你们能帮助我。
答案 0 :(得分:1)
我建议你使用gson库来安卓android。它提供了从json对象解析的简单函数。 看看这个库:https://github.com/google/gson
答案 1 :(得分:1)
你改变了你的功能而不是你想要的[{} {}]
试试这个:
public static String constructJSON(Integer[] array, String[] array2) {
try {
JSONArray firstArray = new JSONArray ();
firstArray.put( array[0]);
firstArray.put( array[1]);
firstArray.put( array[2]);
firstArray.put( array[3]);
firstArray.put( array[4]);
JSONArray secondArray = new JSONArray ();
secondArray.put(array2[0]);
secondArray.put( array2[1]);
secondArray.put( array2[2]);
secondArray.put( array2[3]);
secondArray.put( array2[4]);
JSONObject JArr = new JSONObject();
JArr.put("firstArr",firstArray);
JArr.put("secondArr", secondArray);
return JArr.toString();
} catch (JSONException e) {
}
return null;
}
这将为您提供您想要的JSon,这是使用它的主要代码:
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("firstArr");
JSONArray secondJsonArr= obj.getJSONArray("secondArr");
for (int k = 0; k < firstJsonArr.size(); k++) {
Log.e("item "+k,"item data : "+firstJsonArr.get(k));
}
for (int j = 0; j < secondJsonArr.size(); j++) {
Log.e("item "+j,"item data : "+secondJsonArr.get(j));
}
这对于练习很有用,但是后来你应该使用一个为你做这类事情的库,比如Gson等...