一、使用 jackson 进行转换
@JsonIgnore
-
作用:在json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。
-
使用方法:一般标记在属性或者方法上,返回的json数据即不包含该属性。
@JsonFormat
// 格式化成自己想要的
@JsonFormat(pattern="yyyy-MM-dd")
private Date birth = new Date();
@JsonInclude(JsonInclude.Include.NON_NULL)
- 作用:在json序列化时如果java bean中属性值为 null ,则这个属性不会被序列化,序列化和反序列化都受影响。
- 使用方法:一般标记在实体类上。
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
private int age;
private String name;
// 加上@JsonIgnore后 hubby 属性不会 序列化和反序列化
@JsonIgnore
private String hubby;
@JsonIgnore
//加上@JsonIgnore后 使之不在json序列化结果当中
// "success": true
public boolean isGirl() {
return false;
}
//省略 构造函数 toString get set
}
@ResponseBody
@RequestMapping("/jsonIgnore")
public List test_JsonIgnore2() {
ArrayList arrayList = new ArrayList(){{
add(new User(1));
add(new User("张三"));
add(new User(18,"蔡徐坤","唱跳rap篮球"));
}};
return arrayList;
}
/**
* 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
* Include.Include.ALWAYS 默认
* Include.NON_DEFAULT 属性为默认值不序列化
* Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
* Include.NON_NULL 属性为NULL 不序列化
*/
@Test
public void test() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
User user = new User(1);
String outJson = mapper.writeValueAsString(user);
System.out.println(outJson);
}
/**
* 记得要把 User 的@JsonInclude(JsonInclude.Include.NON_NULL) 取消,不然看不到效果
*/
@Test
public void test02() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
User user2 = new User(18);
String outJson2 = mapper.writeValueAsString(user2);
System.out.println(outJson2);
}
<!--把json转换成对象,对象转换成json 需要用到的jar包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13-beta-2</version>
</dependency>
二、使用Alibaba的fastjson
https://www.w3cschool.cn/fastjson/
@JSONField(serialize = false)
和 @JsonIgnore 效果一样
import com.alibaba.fastjson.annotation.JSONField;
public class User {
private int age;
private String name;
@JSONField(serialize = false)
private String hubby;
@JSONField(serialize = false)
public boolean isGirl() {
return false;
}
// 省略 ...
}
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>