FastJSON如何控制是否序列化null值?
时间: 2024-11-15 11:32:36 浏览: 85
在FastJSON中,你可以通过`JSONObject.toJSONString(Object obj, boolean writeMapNullValue, SerializerFeature... features)`方法来控制是否序列化null值。`writeMapNullValue`参数就是用来决定是否写入空(null)字段的关键。如果设置为`true`,则会在序列化的JSON中显示空字段;若为`false`(默认),空字段就会被忽略。
例如:
```java
String jsonString = JSONObject.toJSONString(obj, true); // 包含空字段
String jsonStringWithoutNulls = JSONObject.toJSONString(obj, false); // 忽略空字段
```
此外,还可以通过`SerializerFeature.WriteMapNullValue`枚举来设置这一特性,比如在构建序列化特征集合时指定:
```java
SerializerFeature feature = new SerializerFeature();
feature.setWriteMapNullValue(true);
JSONObject.toJSONString(obj, feature);
```
相关问题
springboot集成redis,并用fastjson2进行序列化,怎么写
首先,在Spring Boot项目中添加Redis和Fastjson的依赖:
```xml
<!-- Redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Fastjson依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
```
接着,在application.yml中配置Redis连接信息:
```yaml
spring:
redis:
host: localhost
port: 6379
password:
database: 0
```
然后,我们可以创建一个RedisUtil类来操作Redis,示例如下:
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 添加缓存
* @param key
* @param value
* @param expireTime
*/
public void set(String key, Object value, long expireTime) {
if (value instanceof String) {
redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().set(key, JSON.toJSONString(value, SerializerFeature.WriteClassName), expireTime, TimeUnit.SECONDS);
}
}
/**
* 获取缓存
* @param key
* @param clazz
* @param <T>
* @return
*/
public <T> T get(String key, Class<T> clazz) {
Object value = redisTemplate.opsForValue().get(key);
return value == null ? null : JSON.parseObject(value.toString(), clazz);
}
/**
* 删除缓存
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
}
```
在上面的代码中,我们使用了Fastjson对对象进行序列化和反序列化,并且在set方法中判断了value的类型,如果是String类型,则直接存储,否则使用Fastjson将对象序列化后再存储。在get方法中,我们先获取缓存的值,然后判断是否为null,如果不为null,则使用Fastjson将值反序列化成指定的class类型。
最后,在需要使用Redis的地方,我们可以注入RedisUtil,然后调用它的方法即可:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private RedisUtil redisUtil;
@GetMapping("/test")
public String test() {
String key = "test";
String value = "hello world";
redisUtil.set(key, value, 60);
String result = redisUtil.get(key, String.class);
return result;
}
}
```
以上就是在Spring Boot项目中集成Redis并使用Fastjson进行序列化的示例。
fastjson2 全局枚举序列化 反序列化
在 fastjson2 中,可以通过实现 SerializerFeature 和 Feature 接口来实现全局枚举的序列化和反序列化。
1. 全局枚举的序列化
可以通过实现 SerializerFeature 接口来实现全局枚举的序列化,例如:
```java
public enum MyEnum {
A, B, C;
}
public class MyEnumSerializer implements ContextValueSerializer, SerializerFeature {
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType,
int features) throws IOException {
if (object == null) {
serializer.getWriter().writeNull();
return;
}
Enum<?> e = (Enum<?>) object;
serializer.getWriter().writeValue(e.ordinal());
}
@Override
public boolean writeAsArray() {
return false;
}
@Override
public boolean writeNull() {
return true;
}
@Override
public boolean writeEnumUsingName() {
return false;
}
@Override
public boolean writeEnumUsingToString() {
return false;
}
@Override
public boolean writeEnumUsingOrdinal() {
return true;
}
@Override
public boolean writeSlashAsSpecial() {
return false;
}
@Override
public boolean writeTabAsSpecial() {
return false;
}
@Override
public boolean writeQuoteCharAsSpecial() {
return false;
}
@Override
public boolean writeSingleQuoteAsChar() {
return false;
}
@Override
public boolean writeClassName() {
return false;
}
@Override
public boolean notWriteDefaultValue() {
return false;
}
@Override
public boolean browserSecure() {
return false;
}
@Override
public boolean writeDateUseDateFormat() {
return false;
}
@Override
public boolean sortField() {
return false;
}
@Override
public boolean writeTab() {
return false;
}
@Override
public boolean prettyFormat() {
return false;
}
@Override
public boolean writeContentLength() {
return false;
}
@Override
public boolean quoteFieldNames() {
return false;
}
@Override
public boolean useSingleQuotes() {
return false;
}
@Override
public boolean writeNonStringValueAsString() {
return false;
}
@Override
public boolean notWriteRootClassName() {
return false;
}
@Override
public boolean beanToArray() {
return false;
}
@Override
public boolean writeBigDecimalAsPlain() {
return false;
}
@Override
public boolean ignoreNonFieldGetter() {
return false;
}
@Override
public boolean writeEnumUsingToStringUsingGlobalSetting() {
return false;
}
@Override
public boolean writeEnumUsingNameUsingGlobalSetting() {
return false;
}
@Override
public boolean writeDirect() {
return false;
}
@Override
public boolean browserCompatible() {
return false;
}
}
```
然后,在初始化 JSON 序列化器时,可以将该序列化器添加到全局的 SerializerFeature 中,例如:
```java
SerializeConfig config = new SerializeConfig();
config.put(MyEnum.class, MyEnumSerializer.INSTANCE);
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, MyEnum.class);
```
这样,无论什么时候序列化 MyEnum 类型的枚举值,都会使用 MyEnumSerializer 中定义的方式进行序列化。
2. 全局枚举的反序列化
可以通过实现 Feature 接口来实现全局枚举的反序列化,例如:
```java
public enum MyEnum {
A, B, C;
}
public class MyEnumFeature implements Feature {
@Override
public int getMask() {
return 0;
}
@Override
public boolean isEnabled(int features) {
return true;
}
@Override
public boolean isEnabled(int features, int feature) {
return true;
}
@Override
public int config(int features, int feature, boolean state) {
if (feature == MyEnumFeature.WRITE_ENUM_USING_ORDINAL.mask) {
return state ? features | MyEnumFeature.WRITE_ENUM_USING_ORDINAL.mask
: features & ~MyEnumFeature.WRITE_ENUM_USING_ORDINAL.mask;
}
return features;
}
public static final MyEnumFeature WRITE_ENUM_USING_ORDINAL = new MyEnumFeature(1);
public static final MyEnumFeature WRITE_ENUM_USING_NAME = new MyEnumFeature(2);
private final int mask;
private MyEnumFeature(int mask) {
this.mask = mask;
}
}
```
然后,在初始化 JSON 解析器时,可以将该 Feature 添加到全局的 Feature 中,例如:
```java
ParserConfig config = new ParserConfig();
config.addCompatibleFeature(MyEnumFeature.WRITE_ENUM_USING_ORDINAL);
JSON.DEFAULT_PARSER_FEATURE |= MyEnumFeature.WRITE_ENUM_USING_ORDINAL.mask;
```
这样,无论什么时候反序列化 MyEnum 类型的枚举值,都会使用 MyEnumFeature 中定义的方式进行反序列化。
阅读全文