首页 > 编程知识 正文

如何遍历jsonarray,java遍历jsonarray

时间:2023-05-05 07:31:16 阅读:201030 作者:2699

JSONArray ja = new JSONArray();

JSONObject jo1 = new JSONObject();

jo1.put("code", "1");

jo1.put("name", "呵呵");

jo1.put("box_code", "1111");

jo1.put("time", "2016");

ja.add(jo1);

JSONObject jo2 = new JSONObject();

jo2.put("code", "2");

jo2.put("name", "史上");

jo2.put("box_code", "2222");

jo2.put("time", "2015");

ja.add(jo2);

JSONObject jo3 = new JSONObject();

jo3.put("code", "3");

jo3.put("name", "方法");

jo3.put("box_code", "3333");

jo3.put("time", "2014");

ja.add(jo3);

JSONObject jo4 = new JSONObject();

jo4.put("code", "4");

jo4.put("name", "呵呵");

jo4.put("box_code", "4444");

jo4.put("time", "2016");

ja.add(jo4);

JSONObject jo5 = new JSONObject();

jo5.put("code", "5");

jo5.put("name", "速冻");

jo5.put("box_code", "5555");

jo5.put("time", "2015");

ja.add(jo5);

System.out.println(ja);

//ja : [{"code":"1","name":"呵呵","box_code":"1111","time":"2016"},{"code":"2","name":"史上","box_code":"2222","time":"2015"},{"code":"3","name":"方法","box_code":"3333","time":"2014"},{"code":"4","name":"呵呵","box_code":"4444","time":"2016"},{"code":"5","name":"速冻","box_code":"5555","time":"2015"}]

 

Map<String, JSONArray> map = new HashMap<String, JSONArray>();

for (Object object : ja) {

  JSONObject jsonObject = (JSONObject) object;

  String time = (String) jsonObject.get("time");

  JSONObject jo = new JSONObject();

  jo.put("code", (String) jsonObject.get("code"));

  jo.put("box_code", (String) jsonObject.get("box_code"));

  if (map.containsKey(time)) {

    JSONArray ja1 = map.get(time);

    ja1.add(jo);

  } else {

    JSONArray ja2 = new JSONArray();

    ja2.add(jo);

    map.put(time, ja2);

  }

}

Set<Entry<String, JSONArray>> entrySet = map.entrySet();

JSONArray jsonArray = new JSONArray();

 

for (Entry<String, JSONArray> entry : entrySet) {

  JSONObject jsonObject = new JSONObject();

  jsonObject.put("time", entry.getKey());

  jsonObject.put("name", "谁谁");

  jsonObject.put("vos", String.valueOf(entry.getValue()));

  jsonArray.add(jsonObject);

}

System.out.println(jsonArray.toString());

//jsonArray : [{"time":"2016","name":"谁谁","vos":[{"code":"1","name":"呵呵","box_code":"1111"},{"code":"4","name":"呵呵","box_code":"4444"}]},{"time":"2015","name":"谁谁","vos":[{"code":"2","name":"史上","box_code":"2222"},{"code":"5","name":"速冻","box_code":"5555"}]},{"time":"2014","name":"谁谁","vos":[{"code":"3","name":"方法","box_code":"3333"}]}]

}

 

 

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。