java JSONArray 遍历方式(2种)
作者:xxBai 时间:2021-09-07 19:52:48
第一种(java8):遍历JSONArray 拼接字符串
public static void main(String[] args) {
JSONArray jSONArray = new JSONArray();
JSONObject jb = new JSONObject();
jb.put("id", 1);
jb.put("name", "s");
jSONArray.add(jb);
JSONObject j1 = new JSONObject();
j1.put("id", 2);
j1.put("name", "s");
jSONArray.add(j1);
StringBuffer sBuffer = new StringBuffer();
jSONArray.stream().forEach(jsonobejct->arrayIdToString((JSONObject) jsonobejct,sBuffer));
System.out.println(sBuffer.toString());
}
private static StringBuffer arrayIdToString(JSONObject jsonobejct,
StringBuffer sBuffer) {
return sBuffer.append(jsonobejct.getInteger("id")).append(",");
}
第二种:for循环遍历
public static void f2(JSONArray ja) {
for(int i=0;i<ja.size();i++) {
System.out.println(ja.getJSONObject(i).get("id"));
}
}
PS:遍历JsonObject
SONObject jsonObject = new JSONObject(s);
然后用Iterator迭代器遍历取值,建议用反射机制解析到封装好的对象中
JSONObject jsonObject = new JSONObject(jsonString);
Iterator iterator = jsonObject.keys();
while(iterator.hasNext()){
key = (String) iterator.next();
value = jsonObject.getString(key);
}
来源:https://www.cnblogs.com/xxbai1123/p/10174081.html
标签:java,JSONArray,遍历
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
executor包执行器功能
2023-07-26 21:07:36
springBoot项目如何实现启动多个实例
2021-09-22 00:13:47
![](https://img.aspxhome.com/file/2023/0/70500_0s.png)
Java 如何实现一个http服务器
2022-03-27 05:40:04
![](https://img.aspxhome.com/file/2023/2/61292_0s.png)
浅谈三分钟学习Java泛型中T、E、K、V、?的含义
2022-09-01 20:12:38
![](https://img.aspxhome.com/file/2023/2/64372_0s.jpg)
浅谈Synchronized和Lock的区别
2023-10-26 04:28:33
Java SE求解汉诺塔问题的示例代码
2022-05-10 23:44:30
![](https://img.aspxhome.com/file/2023/1/61291_0s.png)
Java Swing JLabel标签的使用方法
2021-09-16 05:48:13
![](https://img.aspxhome.com/file/2023/3/68573_0s.jpg)
MyBatis特殊字符转义拦截器问题针对(_、\\、%)
2023-09-12 00:46:39
![](https://img.aspxhome.com/file/2023/1/78981_0s.png)
一起来了解Java的File类和IO流
2022-04-12 09:23:15
![](https://img.aspxhome.com/file/2023/9/74969_0s.png)
Java实现查找当前字符串最大回文串代码分享
2023-07-30 04:05:02
Java 通过AQS实现数据组织
2023-04-05 22:19:29
![](https://img.aspxhome.com/file/2023/2/63072_0s.png)
Maven的porfile与SpringBoot的profile结合使用案例详解
2023-11-14 00:07:59
![](https://img.aspxhome.com/file/2023/2/58752_0s.png)
Java如何在 Word 中设置上、下标
2023-10-15 21:04:10
![](https://img.aspxhome.com/file/2023/2/77972_0s.png)
基于C#方法重载的总结详解
2022-07-29 13:19:46
java中String.intern()方法功能介绍
2023-11-25 23:49:21
简述Mybatis增删改查实例代码
2023-03-06 18:07:53
![](https://img.aspxhome.com/file/2023/1/65311_0s.png)
Java用 Rhino/Nashorn 代替第三方 JSON 转换库
2023-11-04 02:20:26
struts2 validation.xml 验证规则代码解析
2021-09-14 22:01:27
Java权重随机的实现方法
2021-10-05 14:27:50
C语言文件操作之fread函数详解
2023-07-06 18:24:15
![](https://img.aspxhome.com/file/2023/7/103077_0s.jpg)