json字符串转换成json数组并遍历属性值

小灰灰 2022-06-15 08:52 282阅读 0赞

方法一:使用Iterator迭代器遍历取值

  1. public class Test
  2. {
  3. /**
  4. * @param args
  5. */
  6. @SuppressWarnings("rawtypes")
  7. public static void main(String[] args)
  8. {
  9. String json = "[{'day1':'work','day2':26},{'day1':123,'day2':28}]";
  10. //将json字符串转化成json数组
  11. JSONArray jsonArray = JSONArray.fromObject(json);
  12. for(int i=0; i<jsonArray.size(); i++){
  13. //得到json数组中的每一个json对象
  14. JSONObject obj = (JSONObject) jsonArray.get(i);
  15. //然后用Iterator迭代器遍历取值
  16. Iterator it = obj.keys();
  17. while (it.hasNext()) {
  18. String key = it.next().toString();
  19. System.out.println("key ----->"+key);
  20. System.out.println("value ----->"+obj.get(key));
  21. }
  22. }
  23. }
  24. }

方法二:使用for循环

  1. public class Test
  2. {
  3. /**
  4. * @param args
  5. */
  6. public static void main(String[] args)
  7. {
  8. String json = "[{'day1':'work','day2':26},{'day1':123,'day2':28}]";
  9. //将json字符串转化成json数组
  10. JSONArray jsonArray = JSONArray.fromObject(json);
  11. for(int i=0; i<jsonArray.size(); i++){
  12. JSONObject jsonObject=jsonArray.getJSONObject(i);
  13. System.out.println("value ----->"+jsonObject.getString("day1"));
  14. }
  15. }
  16. }

发表评论

表情:
评论列表 (有 0 条评论,282人围观)

还没有评论,来说两句吧...

相关阅读