alibaba / alibaba/fastjson2

[QUESTION] 有没有办法设置ContextValueFilter不略过NULL

Open
#2,885 0 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

我正在为一个项目做升级,从以前的FastJson升级到FastJson2.0.52

其中有一个需求是需要通过ContextValueFilter去为一些Null值的field做一些后期的处理。

代码如下:
```java
@Override
public void configureMessageConverters(
List> converters) {
FastJsonHttpMessageConverter messageConverter =
new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
messageConverter.setSupportedMediaTypes(
Arrays.asList(MediaType.APPLICATION_JSON_UTF8,
new MediaType(MediaType.APPLICATION_XML, StandardCharsets.UTF_8),
new MediaType(MediaType.TEXT_HTML, StandardCharsets.UTF_8)));
config.setDateFormat("millis");
messageConverter.setFastJsonConfig(config);
Filter[] filters = {new TranslateFilter(messageSource)};
messageConverter.getFastJsonConfig().setWriterFilters(filters);
converters.add(messageConverter);
}
```
TranslateFilter是extends ContextValueFilter去做后期的处理

```java

@Data
@Builder
@NoArgsConstructor
@ALLArgsConstructor
public class LastGameInfo {
private String id;
private String txt;
private String game;
private String gameName; // 这个初始值会是null
private String gameText; // 这个初始值会是null
}
```

我试着在TranslateFilter里边去debug,发现它略过了 gameName 跟 gameText (如果把他们初始成 "" 就不会有问题)。
我试过了如果在FastJsonConfig 去设置WriteFeature然后JSONWriterFeature.Feature.WriteNulls 就能一部分解决我的问题,但是会导致其他不需要被后期处理的 null field 也一同发送了去前端。

想问问各位大佬是否有合适的解决方案来解决我这个问题呀?

Contributor guide

Open the contributing guide

Research direction

Start by examining the TranslateFilter implementation that extends ContextValueFilter and the FastJsonConfig writer-filter setup shown in the issue. Reproduce serialization of LastGameInfo with gameName and gameText null, compare it with WriteNulls enabled, and determine whether selective post-processing of null fields can be supported without emitting unrelated null fields.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.