SerializerFeature主要属性
名称 | 含义 |
---|---|
QuoteFieldNames | 输出key时是否使用双引号,默认为true |
UseSingleQuotes | 使用单引号而不是双引号,默认为false |
WriteMapNullValue | 是否输出值为null的字段,默认为false,不输出null字段 |
WriteNullListAsEmpty | List字段如果为null,输出为[],而非null ,默认false,输出值为null |
WriteNullStringAsEmpty | 字符类型字段如果为null,输出为"",而非null,默认false,输出值为null |
WriteNullNumberAsZero | 数值字段如果为null,输出为0,而非null,默认false,输出值为null |
WriteNullBooleanAsFalse | Boolean字段如果为null,输出为false,而非null,默认false,输出值为null |
测试类 BeanA
@Data
public class BeanA {
private String testString;
private Integer testInt;
private Boolean testBoolean;
private List<BeanB> testList;
}
- WriteMapNullValue
public static void main(String[] args) {
BeanA beanA = new BeanA();
beanA.setTestString("上海市");
System.out.println(JSONObject.toJSONString(beanA));
System.out.println(JSONObject.toJSONString(beanA,SerializerFeature.WriteMapNullValue));
}
{“testString”:“上海市”}
{“testBoolean”:null,“testInt”:null,“testList”:null,“testString”:“上海市”}
- UseSingleQuotes
public static void main(String[] args) {
BeanA beanA = new BeanA();
beanA.setTestString("上海市");
System.out.println(JSONObject.toJSONString(beanA));
System.out.println(JSONObject.toJSONString(beanA,SerializerFeature.UseSingleQuotes ));
}
{“testString”:“上海市”}
{‘testString’:‘上海市’}
- WriteNullListAsEmpty
public static void main(String[] args) {
BeanA beanA = new BeanA();
beanA.setTestString("上海市");
System.out.println(JSONObject.toJSONString(beanA));
System.out.println(JSONObject.toJSONString(beanA,SerializerFeature.WriteNullListAsEmpty ));
}
{“testString”:“上海市”}
{“testList”:[],“testString”:“上海市”}
- WriteNullStringAsEmpty
public static void main(String[] args) {
BeanA beanA = new BeanA();
beanA.setTestInt(10);
System.out.println(JSONObject.toJSONString(beanA));
System.out.println(JSONObject.toJSONString(beanA,SerializerFeature.WriteNullStringAsEmpty ));
}
{“testInt”:10}
{“testInt”:10,“testString”:""}
- WriteNullNumberAsZero
public static void main(String[] args) {
BeanA beanA = new BeanA();
beanA.setTestString("上海市");
System.out.println(JSONObject.toJSONString(beanA));
System.out.println(JSONObject.toJSONString(beanA,SerializerFeature.WriteNullNumberAsZero ));
}
{“testString”:“上海市”}
{“testInt”:0,“testString”:“上海市”}
- WriteNullBooleanAsFalse
public static void main(String[] args) {
BeanA beanA = new BeanA();
beanA.setTestString("上海市");
System.out.println(JSONObject.toJSONString(beanA));
System.out.println(JSONObject.toJSONString(beanA,SerializerFeature.WriteNullBooleanAsFalse ));
}
{“testString”:“上海市”}
{“testBoolean”:false,“testString”:“上海市”}
- WRITE_MAP_NULL_FEATURES
集合了WriteMapNullValue,WriteNullListAsEmpty,WriteNullStringAsEmpty,WriteNullNumberAsZero,WriteNullBooleanAsFalse
public static void main(String[] args) {
BeanA beanA = new BeanA();
System.out.println(JSONObject.toJSONString(beanA));
System.out.println(JSONObject.toJSONString(beanA,SerializerFeature.WRITE_MAP_NULL_FEATURES ));
}
{}
{testInt:0,testList:[],testBoolean:false,testString:""}