alibaba / alibaba/fastjson2

[QUESTION]如何在自定义序列化时实现某条件满足时忽略该字段的序列化

Open
#2,214 3 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Java
Stars
4.4k
Forks
613
Avg merge
1d 22h
Merged PRs (30d)
6

Description

User.java
```
import com.alibaba.fastjson2.annotation.JSONField;

public class User {
/**
其他字段...
*/
@JSONField(serializeUsing = NotWriteEmptyString.class)
private String career;
}
```

NotWriteEmptyString.java
```
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.writer.ObjectWriter;
import java.lang.reflect.Type;

public class NotWriteEmptyString implements ObjectWriter {
@Override
public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
if ("".equals(object)) {
jsonWriter.writeNull();
}
}
}
```

**想要实现的效果是如果字符串属性的值为空字符串就不进行序列化返回给前端**。
而按照上面的方式,前端收到的数据只是相应属性变成了null值。
请问我要怎么做?

相关依赖:
jdk: 1.8
maven:
```

org.springframework.boot
spring-boot-starter-parent
2.7.9



com.alibaba.fastjson2
fastjson2
2.0.43


com.alibaba.fastjson2
fastjson2-extension-spring5
2.0.43

```

Contributor guide

Open the contributing guide

Research direction

Start by reading the User.java example and NotWriteEmptyString.java implementation, then inspect the fastjson2 serialization behavior relevant to JSONField.serializeUsing. The issue does not name a test or repository entry point; done would require identifying and documenting a supported way to omit empty-string fields rather than emitting null.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend-api-design
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.