如何使用json.toJSONString包含null字段
默认情况下,json.toJSONString方法会忽略为null的字段。如果想要包含为null的字段,可以使用Gson库或者自定义JSONSerializer来实现。
使用Gson库的示例代码如下:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
SampleObject sampleObject = new SampleObject();
sampleObject.setName('John');
// 将null字段包含在JSON字符串中
gson.toJson(sampleObject); // {'name':'John','age':null}
}
}
class SampleObject {
private String name;
private Integer age;
// getters and setters
}
使用自定义JSONSerializer的示例代码如下:
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class Main {
public static void main(String[] args) {
SampleObject sampleObject = new SampleObject();
sampleObject.setName('John');
// 将null字段包含在JSON字符串中
JSONObject jsonObject = JSONObject.fromObject(sampleObject, getJsonConfig());
System.out.println(jsonObject.toString()); // {'name':'John','age':null}
}
private static JsonConfig getJsonConfig() {
JsonConfig config = new JsonConfig();
config.registerJsonValueProcessor(Object.class, new JsonValueProcessor() {
@Override
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return value;
}
@Override
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
return value;
}
});
return config;
}
}
class SampleObject {
private String name;
private Integer age;
// getters and setters
}
这两种方法都可以将为null的字段包含在生成的JSON字符串中。
原文地址: https://www.cveoy.top/t/topic/blNE 著作权归作者所有。请勿转载和采集!