使用java将json对象转换为两个数组

时间:2013-10-24 23:21:56

标签: java android arrays json

Hello有没有办法将这个json对象转换成两个数组?我已经尝试了下面的代码,它工作正常,但我没有将json对象转换为两个数组,一个名为'id',另一个数组称为'name'。我怎么能这样做呢。这是我走了多远

 int[] id= {};
 String[] names={};

myfunction = new myFunctions();
    json = userfunction.petitions();

    try {
        if (json.get(KEY_SUCCESS) != null) {
            String rs = json.getString(KEY_SUCCESS);
            if (Integer.parseInt(rs) == 1) {
                inserting ids into id array here....
                inserting names into names array here..
            }

        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

并且json对象是

10-25 02:08:54.325: E/JSON(406): {"success":1,"petitions":[{"id":"1","name":"Has        Jennifer Musisi done great work for Kampala","timestamp":"2013-10-24 14:32:58"},{"id":"2","name":"Do lecturers deserve 100% salary increase","timestamp":"2013-10-24 14:32:58"},{"id":"3","name":"Olara Otunu should get married","timestamp":"2013-10-24 14:33:53"},{"id":"4","name":"Teachers deserve 30 not 20 salary rise","timestamp":"2013-10-24 14:33:53"},{"id":"5","name":"Prostitution should be banned","timestamp":"2013-10-24 14:33:53"}]}

2 个答案:

答案 0 :(得分:0)

petitions是一个JSON数组,因此您可以创建一个JSONArray对象,捕获值,然后从数组中获取字符串。

例如:

id[0] = myArray[0].getString("id");
names[0] = myArray[0].getString("names");

将其放入myArray.length()

的for循环中

答案 1 :(得分:0)

JSONArray jar=json.getJSONArray("petitions");
 int len=jar.length();
for(int ctr=0;ctr<len;ctr++)
{
 JSONObject job =  jar.getI(ctr);   


}

希望这会有所帮助。