问题描述:
将实体类加到map 里,然后将map 转为 JSON 会出现实体类里字段只为null的字段丢失。将map 转为String 又不会丢失。
解决思路:
将map 里所有实体类的字段为null 的转为"",空字符。这样转过""的map 转json ,就不会出现字段丢失的问题了。
解决步骤:
一,将map 里字段值为null转为""
1.1 创建 JsonDealUtils 工具类,继承ObjectMapper
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
/**
* @author: zjk
* @Description: JSON重新序列化逻辑
* @date: 2022/6/16 22:23
*/
public class JsonDealUtils extends ObjectMapper {
public JsonDealUtils() {
super();
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException, JsonProcessingException {
arg1.writeString("");
}
});
}
}
1.2 将map 为null 字段转为"",返回值为String 类型
Map<String, Object> param = new HashMap<>();
param.put("data", data);
param.put("finishState", qcPartition.getFinishState());
param.put("finishState", qcPartition.getFinishState());
ObjectMapper objectMapper = new JsonDealUtils();
String string = objectMapper.writeValueAsString(param);
1.3 将String 转为JSON
JSONObject parse = JSONObject.parseObject(string);
这时值为null 的字段就转为了"",