import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonExample {
public static void main(String[] args) {
try {
// 创建一个对象映射器
ObjectMapper objectMapper = new ObjectMapper();
// 设置序列化特性,不输出空值
objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
// 创建一个示例对象
ExampleObject exampleObject = new ExampleObject("name", null, "value");
// 将对象转换为 JSON 字符串
String jsonString = objectMapper.writeValueAsString(exampleObject);
// 输出 JSON 字符串
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ExampleObject {
private String name;
private String nullableField;
private String value;
public ExampleObject(String name, String nullableField, String value) {
this.name = name;
this.nullableField = nullableField;
this.value = value;
}
// Getters and setters are omitted for brevity
}
JsonInclude.Include.NON_NULL,可以确保在序列化时忽略所有值为 null 的字段。name、nullableField 和 value。其中 nullableField 被设置为 null。这段代码会输出如下 JSON 字符串(注意 nullableField 没有出现在结果中,因为它为 null):
{"name":"name","value":"value"}
上一篇:java 日期格式
下一篇:java线程池的工作原理
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站