<!-- json解析用 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<!-- 简化代码,方便日志打印 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
@Data
@AllArgsConstructor
public class Student implements Serializable,Cloneable {
private static final long serialVersionUID = 6447932156561222739L;
private Integer sNo;
private String name;
private Date birthday;
private Integer classNo;
private String grade;
/**
* 方便对象复制
* @return
* @throws CloneNotSupportedException
*/
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
}
- 实体转json
Student s1 = new Student(1,"张三",new Date(),1001,"一年级");
String s1Json = JSON.toJSONString(s1);
log.info("fastjson将Student转的json为{}",s1Json);
- Map转json
Student s1 = new Student(1,"张三",new Date(),1001,"一年级");
Student s2 = s1.clone();
s2.setSNo(2);
Student s3 = s1.clone();
s3.setSNo(3);
Student s4 = s1.clone();
s4.setSNo(4);
Map<String,Student> data = new LinkedHashMap();
data.put("s1",s1);
data.put("s2",s2);
data.put("s3",s3);
data.put("s4",s4);
String mapJson = JSON.toJSONString(data);
log.info("fastjson将map转的json为{}",mapJson);
- List转json
Student s1 = new Student(1,"张三",new Date(),1001,"一年级");
Student s2 = s1.clone();
s2.setSNo(2);
Student s3 = s1.clone();
s3.setSNo(3);
Student s4 = s1.clone();
s4.setSNo(4);
List<Student> studentList = new ArrayList<>(Arrays.asList(s1,s2,s3,s4));
String listJson = JSON.toJSONString(studentList);
log.info("fastjson将List转的json为{}",listJson);
- json转实体
Student s1 = new Student(1,"张三",new Date(),1001,"一年级");
String s1Json = JSON.toJSONString(s1);
log.info("fastjson将Student转的json为{}",s1Json);
Student json1Student = JSON.parseObject(s1Json,Student.class);
log.info("json转实体Student结果:{}",json1Student);
- json转Map
Student s1 = new Student(1,"张三",new Date(),1001,"一年级");
Student s2 = s1.clone();
s2.setSNo(2);
Student s3 = s1.clone();
s3.setSNo(3);
Student s4 = s1.clone();
s4.setSNo(4);
Map<String,Student> data = new LinkedHashMap();
data.put("s1",s1);
data.put("s2",s2);
data.put("s3",s3);
data.put("s4",s4);
String mapJson = JSON.toJSONString(data);
log.info("fastjson将map转的json为{}",mapJson);
Map<String,Student> json2map = JSON.parseObject(mapJson,Map.class);
log.info("json转Map结果:{}",json2map);
- json转List
Student s1 = new Student(1,"张三",new Date(),1001,"一年级");
Student s2 = s1.clone();
s2.setSNo(2);
Student s3 = s1.clone();
s3.setSNo(3);
Student s4 = s1.clone();
s4.setSNo(4);
List<Student> studentList = new ArrayList<>(Arrays.asList(s1,s2,s3,s4));
String listJson = JSON.toJSONString(studentList);
log.info("fastjson将List转的json为{}",listJson);
List<Student> json2List = JSON.parseObject(listJson,new TypeReference<List<Student>>(){});
log.info("json转List结果:{}",json2List);
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Fastjson的基本用法
发表评论 取消回复