将json对象转换为多个数组android

时间:2016-02-10 21:34:33

标签: android arrays json

我从我的服务器下载了一个json对象,该对象以下列格式返回结果:

{"Bookname":["Alive-O","All Write Now ","Bun Go Barr 1","Planet Maths","Small World"],"SubjectName":["Religion","English","Irish","Maths","Science"]}

我想要做的是将其转换为两个不同的数组,以便在Android设备上使用。

这是请求,并在我的asynctask中寻找响应

        String[] BookName;
        String[] BookSubject;
        try {
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            HttpResponse httpResponse = client.execute(post);

            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jObject = new JSONObject(result);


        } 

只是想知道如何将上述结果存储在两个数组中?

2 个答案:

答案 0 :(得分:1)

鉴于您选择JSONObject,您的JSON是那种不寻常的结构,并且您希望在Java中镜像该结构:

步骤1:在getJSONArray()上致电jObject()两次,获取两个JSONArray个对象(BooknameSubjectName

步骤2:将每个String[]分配为合适的长度(length()上的JSONArray

}

步骤3:对于每个JSONArray,循环遍历数组索引(0到length())并为每个索引调用getString(),将其分配给关联的{中的相应索引{ {1}}

答案 1 :(得分:1)

就像这样

    JSONObject jsonObject = new JSONObject(result);

    // for getting booknames
    JSONArray jsonArray = jsonObject.getJSONArray("Bookname");
    bookName = new String[jsonArray.length()]
    for (int i = 0; i < jsonArray.length(); i++) {
        bookName[i] = jsonArray.getString(i);
    }

    // for getting subjectnames
    jsonArray = jsonObject.getJSONArray("SubjectName");
    bookSubject = new String[jsonArray.length()]
    for (int i = 0; i < jsonArray.length(); i++) {
        bookSubject[i] = jsonArray.getString(i);
    }

希望它会有所帮助.. !!