从json获取数组不起作用

时间:2018-07-31 11:04:06

标签: java android arrays

当前,我正在一个项目中,我需要从远程服务器获取一些数据(如JSON),然后需要提取数组。在这里,我正在成功获取数据,但是问题在while循环附近。

我正在从远程服务器成功获取数据。 例如,我的远程URL输出为:

{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},
{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}`

代码

try {
        ur = "http://localhost/getsample.php";
        URL url = new URL(ur);
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line="";




        while (line !=null){
            line = bufferedReader.readLine();
            data = data+line;
        }
        data = data.replace("null", "");

        JSONArray JA = new JSONArray(data);
        for (int i=0;i<JA.length();i++){
            JSONObject JO = (JSONObject) JA.get(i);
 idArray = idArray + JO.get("id") + ",";
            amountArray = amountArray + JO.get("amount") + ",";
            course_codeArray = course_codeArray + JO.get("course_code") + ",";
            courseArray = courseArray + JO.get("course") + ",";
            contentArray = contentArray + JO.get("content") + ",";
            thumbArray = thumbArray + JO.get("thumb") + ",";
        }


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:1)

从服务器获取的数据为JSON格式,但不是Array。这是一个对象,

{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}

所以您必须在

之类的json对象中循环
for (var key in jsonResponse) {
    if (jsonResponse.hasOwnProperty(key)) {
        console.log(key + " -> " + jsonResponse[key]);
    }
}

编辑:如果一个对象中有多个对象,则必须像for(var i in JsonObject)那样在它们内部(外部)循环

答案 1 :(得分:0)

您的代码应类似于根据您当前的Response

try{
 JSONObject jso = new JSONObject(data);
            amountArray =jsonObject.getString("amount");
            course_codeArray =jsonObject.getString("yourNextKey");
            courseArray = jsonObject.getString("yourNextKey");
            contentArray = jsonObject.getString("yourNextKey");
            thumbArray = jsonObject.getString("yourNextKey");
        }
 catch (JSONException e) {
            e.printStackTrace();
        }