1、首先在pom.xml中添加注解,加载阿里的jar包
<!-- 阿里的json工具包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>2、然后在java文件中调用
public static void main(String[] args) {
//定义object类型的字符串
String str = "{label : '短信通知',code1 : 'name',code2 : 'date'}";
//转换字符串为JSONObject
JSONObject jsStr = JSONObject.parseObject(str);
//进行遍历输出
Set<Entry<String, Object>> entrySet = jsStr.entrySet();
//输出长度
System.out.println(entrySet.size());
for (Entry<String, Object> s : entrySet) {
//输出key+value
System.out.println(s.getKey() + "+" + s.getValue());
}
}3、输出结果:
3
code2+date
code1+name
label+短信通知
本文介绍了如何通过阿里FastJSON库将JSON字符串转换为Java对象并进行遍历操作的方法。主要内容包括:在pom.xml中引入FastJSON依赖,使用FastJSON的parseObject方法将JSON字符串解析成JSONObject对象,并通过entrySet遍历输出。
2591

被折叠的 条评论
为什么被折叠?



