如果你在使用 Fastjson 库将 Java 对象转换为 JSON 字符串时,想要排除某个字段,你可以使用以下几种方法:
在 Java 中,transient 关键字用于表示一个字段不应当被序列化。当你使用 Fastjson 对对象进行序列化时,transient 修饰的字段将不会被包含在内。
简单示例:
package com.hxstrive.fastjson;
import com.alibaba.fastjson.JSONObject;
/**
* 设置 Fastjson 不被序列化部分字段
* @author hxstrive.com
*/
public class FastjsonDemo {
public static void main(String[] args) {
User user = new User(1, "张三", "男");
System.out.println(JSONObject.toJSONString(user, true));
}
}
class User {
private int id;
private String name;
// 该字段不会被序列化
private transient String sex;
public User(int id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
}运行示例,输出如下:
{
"id":1,
"name":"张三"
}Fastjson 提供了 @JSONField 注解,允许你更精细地控制字段的序列化和反序列化行为。通过设置 serialize 属性为 false,你可以指定某个字段在序列化时被排除。
简单示例:
package com.hxstrive.fastjson;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 设置 Fastjson 不被序列化部分字段
* @author hxstrive.com
*/
public class FastjsonDemo2 {
public static void main(String[] args) {
User user = new User(1, "张三", "男");
System.out.println(JSONObject.toJSONString(user, true));
}
static class User {
private int id;
private String name;
// 该字段不序列化
@JSONField(serialize = false)
private String sex;
public User(int id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
}
}运行示例,输出如下:
{
"id":1,
"name":"张三"
}如果你想要在运行时动态地决定哪些字段被序列化,你可以使用 com.alibaba.fastjson.serializer.PropertyFilter,这种方法比使用注解或 transient 关键字更加灵活。
简单示例:
package com.hxstrive.fastjson;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* 设置 Fastjson 不被序列化部分字段
* @author hxstrive.com
*/
public class FastjsonDemo3 {
public static void main(String[] args) {
User user = new User(1, "张三", "男");
System.out.println(JSONObject.toJSONString(user, new PropertyFilter() {
@Override
public boolean apply(Object source, String name, Object value) {
System.out.println("name:" + name + ", value:" + value);
// 返回 false 来排除字段
return !"sex".equals(name);
}
}, SerializerFeature.PrettyFormat));
}
static class User {
private int id;
private String name;
private String sex;
public User(int id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
}
}在上面的示例中,我们创建了一个匿名的 PropertyFilter 实现,它根据字段名来决定是否序列化该字段。通过返回 false,我们告诉 Fastjson 排除名为 "sex" 的字段。
运行示例,输出如下:
name:id, value:1
name:name, value:张三
name:sex, value:男
{
"id":1,
"name":"张三"
}