使用 PropertyPreFilters.MySimplePropertyPreFilter:

PropertyPreFilters filters = new PropertyPreFilters();
PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
excludefilter.addExcludes("user", "corp", "store");
String originalContent = JSON.toJSONString(old, excludefilter, SerializerFeature.WriteMapNullValue);

这里可以 添加忽略属性,也可以添加包含属性,addExcludes addIncludes 


使用 SimplePropertyPreFilter:

    SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
    filter.getExcludes().add("user");
    filter.getExcludes().add("corp");
    filter.getExcludes().add("store");

    String json = JSON.toJSONString(old, filter, SerializerFeature.WriteMapNullValue);

这里也可能过,构造函数将 包含的属性批量添加进去,如下构造函数:

    public SimplePropertyPreFilter(String... properties){
        this(null, properties);
    }

    public SimplePropertyPreFilter(Class<?> clazz, String... properties){
        super();
        this.clazz = clazz;
        for (String item : properties) {
            if (item != null) {
                this.includes.add(item);
            }
        }
    }

其它情况设置:

String jsonUser = null;
/**
 * 情况一:默认忽略值为null的属性
 */
jsonUser = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat);
System.out.println("情况一:" + jsonUser);

/**
 * 情况二:包含值为null的属性
 */
jsonUser = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
System.out.println("情况二:" + jsonUser);

/**
 * 情况三:默认忽略值为null的属性,但是排除country和city这两个属性
 */
jsonUser = JSONObject.toJSONString(user, excludefilter, SerializerFeature.PrettyFormat);
System.out.println("情况三:" + jsonUser);

/**
 * 情况四:包含值为null的属性,但是排除country和city这两个属性
 */
jsonUser = JSONObject.toJSONString(user, excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
System.out.println("情况四:" + jsonUser);

/**
 * 情况五:默认忽略值为null的属性,但是包含id、username和mobile这三个属性
 */
jsonUser = JSONObject.toJSONString(user, includefilter, SerializerFeature.PrettyFormat);
System.out.println("情况五:" + jsonUser);

/**
 * 情况六:包含值为null的属性,但是包含id、username和mobile这三个属性
 */
jsonUser = JSONObject.toJSONString(user, includefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
System.out.println("情况六:" + jsonUser);