maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
Java对象
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class Student {
private Long id;
private String name;
private Integer heInteger;
}
单元测试
@Test
public void testJson() {
System.out.println("======================");
Student student = new Student();
student.setId(2L);
student.setName("guest");
Student rootUser = new Student();
rootUser.setId(3L);
rootUser.setName("root");
// 转换为 JSON
String jsonString = JSON.toJSONString(student);
System.out.println("JSON字符串:" + jsonString);
// 转换为 对象BEAN
Student grade = JSON.parseObject(jsonString, Student.class);
System.out.println("JavaBean对象:" + JsonUtils.toString(grade));
String s2 = JSON.toJSONString(jsonString, SerializerFeature.WriteMapNullValue);
System.out.println("JSON字符串2:" + s2);
String s3 = JSON.toJSONString(student, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse);
System.out.println("JSON字符串3:" + s3);
String nowDate = JSON.toJSONStringWithDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
System.out.println("当前时间====:" + nowDate);
Group group = new Group();
List<Student> list = Lists.newArrayList();
list.add(student);
list.add(rootUser);
group.setList(list);
String s4 = JSON.toJSONString(list);
System.out.println("JSON字符串s4:" + s4);
List<Student> students = JSON.parseArray(s4, Student.class);
}