FastJson
java对象转json字符串
1.java对象
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
private Integer id;
private String name;
private Integer grade; //年纪 1~6
private String sex; //性别
private Boolean flag;
public Student(Integer id, String name, Integer grade, String sex) {
this.id = id;
this.name = name;
this.grade = grade;
this.sex = sex;
}
public Student(Integer id, String name, Integer grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
2.将java对象转换为json字符串
package cn.zhw.fastjson.test;
import cn.zhw.fastjson.entity.Student;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import java.util.HashMap;
public class FastJsonTest {
//将java对象转换为json数据
@Test
public void test1(){
//学生对象方法
Student student = new Student(1, "张国荣", 6, "男");
//将java对象转换为接送数据方法
String s = JSON.toJSONString(student);
System.out.println(s); //{"grade":6,"id":1,"name":"张国荣","sex":"男"}
Student student1 = new Student(1, "张国荣", 6);
String s1 = JSON.toJSONString(student);
//当对象的Field为null是不会序列化该值
System.out.println(s); //{"grade":6,"id":1,"name":"张国荣"}
}
}
list集合转json字符串
//将list集合转换为json数据
@Test
public void test2(){
ArrayList<Object> list = new ArrayList<>();
list.add("张国荣");
list.add("王祖贤");
list.add("古天乐");
String s = JSON.toJSONString(list);
System.out.println(s); //["张国荣","王祖贤","古天乐"]
}
map集合转json字符串
//将map集合转换为json数据
@Test
public void test3(){
HashMap<Object, Object> map = new HashMap<>();
map.put("name","张国荣");
map.put("age",21);
String s = JSON.toJSONString(map);
System.out.println(s); //{"name":"张国荣","age":21}
}
Json数据转成java对象
//将json数据转换为java对象
@Test
public void test4(){
//json字符串
String json = "{\"id\":21,\"name\":\"张国荣\",\"grade\":3,\"sex\":\"男\"}";
//将字符串转换为student对象
Student student = JSON.parseObject(json, Student.class);
System.out.println(student); //Student(id=21, name=张国荣, grade=3, sex=男)
}
Json数据转成list集合
//将json数据转换为list集合
@Test
public void test5(){
//json字符串
String json = "[\"郑浩文\",\"郑奥运\",\"郑世豪\"]";
//将字符串转换为student对象
List<String> strings = JSON.parseArray(json, String.class);
strings.stream().forEach(System.out::println); //郑浩文 郑奥运 郑世豪
System.out.println(strings); //[郑浩文, 郑奥运, 郑世豪]
}
# Json数据转成map集合
//将json数据转换为map集合
@Test
public void test6(){
//json字符串
String json = "{\"name\":\"张国荣\",\"age\":21}";
JSONObject jsonObject = JSON.parseObject(json);
Object name = jsonObject.get("name");
System.out.println(name); //张国荣
System.out.println(name.getClass()); //class java.lang.String
Object age = jsonObject.get("age");
System.out.println(age); //21
System.out.println(age.getClass()); //class java.lang.Integer
}
SerializerFeature枚举
当进行序列化的时候可以根据我们的需要指定序化的方式,该枚举类型就包含了这些方式
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.alibaba.fastjson.serializer;
public enum SerializerFeature {
QuoteFieldNames,
UseSingleQuotes,
WriteMapNullValue,
WriteEnumUsingToString,
WriteEnumUsingName,
UseISO8601DateFormat,
WriteNullListAsEmpty,
WriteNullStringAsEmpty,
WriteNullNumberAsZero,
WriteNullBooleanAsFalse,
SkipTransientField,
SortField,
/** @deprecated */
@Deprecated
WriteTabAsSpecial,
PrettyFormat,
WriteClassName,
DisableCircularReferenceDetect,
WriteSlashAsSpecial,
BrowserCompatible,
WriteDateUseDateFormat,
NotWriteRootClassName,
/** @deprecated */
DisableCheckSpecialChar,
BeanToArray,
WriteNonStringKeyAsString,
NotWriteDefaultValue,
BrowserSecure,
IgnoreNonFieldGetter,
WriteNonStringValueAsString,
IgnoreErrorGetter,
WriteBigDecimalAsPlain,
MapSortField;
public final int mask = 1 << this.ordinal();
public static final SerializerFeature[] EMPTY = new SerializerFeature[0];
public static final int WRITE_MAP_NULL_FEATURES = WriteMapNullValue.getMask() | WriteNullBooleanAsFalse.getMask() | WriteNullListAsEmpty.getMask() | WriteNullNumberAsZero.getMask() | WriteNullStringAsEmpty.getMask();
private SerializerFeature() {
}
public final int getMask() {
return this.mask;
}
public static boolean isEnabled(int features, SerializerFeature feature) {
return (features & feature.mask) != 0;
}
public static boolean isEnabled(int features, int featuresB, SerializerFeature feature) {
int mask = feature.mask;
return (features & mask) != 0 || (featuresB & mask) != 0;
}
public static int config(int features, SerializerFeature feature, boolean state) {
if (state) {
features |= feature.mask;
} else {
features &= ~feature.mask;
}
return features;
}
public static int of(SerializerFeature[] features) {
if (features == null) {
return 0;
} else {
int value = 0;
SerializerFeature[] var2 = features;
int var3 = features.length;
for(int var4 = 0; var4 < var3; ++var4) {
SerializerFeature feature = var2[var4];
value |= feature.mask;
}
return value;
}
}
}
SerializerFeature枚举的使用
1.对象的null值field也序列化
//SerializerFeature的使用,序列化的方案,将javaBean的Field为null的值,序列化值为null
@Test
public void test7(){
Student student = new Student(2, "王祖贤", 4);
//设定将null也序列化的方案
String s1 = JSON.toJSONString(student, SerializerFeature.WriteMapNullValue);
System.out.println(s1); //{"grade":4,"id":2,"name":"王祖贤","sex":null}
String s2 = JSON.toJSONString(s将tudent);
System.out.println(s2); //{"grade":4,"id":2,"name":"王祖贤"}
}
2.将为空的字符串或者数值Filed序列化为""或0
//SerializerFeature的使用,序列化的方案,将javaBean的Field为null的值,序列化值为""
@Test
public void test8(){
Student student = new Student(2, "王祖贤", 4);
student.setGrade(null);
//设定将null也序列化的方案
String s1 = JSON.toJSONString(student, SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero);
System.out.println(s1); //{"grade":0,"id":2,"name":"王祖贤","sex":""}
}
@JsonField注解的使用
该注解作用于要进行序列化的对象的方法,字段和方法的参数上,用于序列化和反序列化时进行特性功能定制
package cn.zhw.fastjson.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
@JSONField(ordinal = 0) //ordinal用于指定序列化后属性的顺序,数值越小越靠前
private Integer id;
@JSONField(name = "studentName",ordinal = 1) //name用于指定序列化后的属性名
private String name;
@JSONField(ordinal = 2,deserialize = false) //是否反序列化该Field
private Integer grade; //年纪 1~6
@JSONField(ordinal = 3)
private String sex; //性别
@JSONField(serialzeFeatures = {SerializerFeature.WriteNullBooleanAsFalse})
private Boolean flag;
@JSONField(format = "yyyy-MM-dd",serialize = false) //format指定格式,当serialize为false时不会序列化该Filed
private Date date;
public Student(Integer id, String name, Integer grade, String sex) {
this.id = id;
this.name = name;
this.grade = grade;
this.sex = sex;
}
public Student(Integer id, String name, Integer grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
//@JsonField的使用
@Test
public void test10(){
Student student = new Student(2, "王祖贤", 4,"男");
student.setDate(new Date());
System.out.println(student);//{"date":1629102237196,"id":2,"studentName":"王祖贤","grade":4,"sex":"男"} date为时间戳
//设定将null也序列化的方案
String s1 = JSON.toJSONString(student);
System.out.println(s1); //没有指定格式之前:{"date":1629102314408,"id":2,"studentName":"王祖贤","grade":4,"sex":"男"}
// {"date":"2021-08-16","id":2,"studentName":"王祖贤","grade":4,"sex":"男"}
}
//@JsonField的使用
@Test
public void test11(){
Student student = new Student(2, "王祖贤", 4,"男");
student.setDate(new Date());
String s = JSON.toJSONString(student,SerializerFeature.WriteMapNullValue);
System.out.println(s); //{"flag":null,"id":2,"studentName":"王祖贤","grade":4,"sex":"男"}
String json = "{\"flag\":null,\"id\":2,\"studentName\":\"王祖贤\",\"grade\":4,\"sex\":\"男\"}";
JSONObject student1 = JSON.parseObject(json);
System.out.println(student1); //{"studentName":"王祖贤","grade":4,"sex":"男","id":2}
}
@JsonType的使用
该注解作用于要序列化的对象上,用于序列化和反序列化时进行特性功能定制
import java.util.Date;
@Data
@JSONType(
includes = {"name","code","age"},
orders = {"name","code","age"},
serialzeFeatures = {SerializerFeature.WriteNullNumberAsZero})
/**
* includes 要被序列化的字段的名字
*/
public class Teacher {
private String name;
private String code;
private Integer age;
private Date date;
private Boolean marriage;
}
//测试@JsonType
@Test
public void test12(){
Teacher teacher = new Teacher();
teacher.setName("zhangmengxing");
teacher.setCode("20000202");
// teacher.setAge(21);
teacher.setDate(new Date());
teacher.setMarriage(false);
System.out.println(teacher); //Teacher(name=zhangmengxing, code=20000202, age=21, date=Mon Aug 16 16:43:41 CST 2021, marriage=false)
String s = JSON.toJSONString(teacher);
System.out.println(s); //{"age":21,"code":"20000202","name":"zhangmengxing"}
}