JSONObject.toJSONString包含或排除指定属性

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JSONObject.toJSONString包含或排除指定属性

小破孩楼主   2022-05-23 我要评论

JSONObject.toJSONString包含或排除指定的属性

将一个实体对象转换成Json字符串 JSON.toJSONString()

FastJson提供的SerializeFilter类可以指定转换时要包含的属性,或者指定转换时要排除的属性。

JSONObject.toJSONString()默认忽略值为null的属性.

使用JSONObject提供的以下方法将实体对象转换成Json字符串:(JSONObject 提供的toJSONString 源码 自己还没看)

public static final String toJSONString(Object object, SerializerFeature... features) {
        SerializeWriter out = new SerializeWriter();
        try {
            JSONSerializer serializer = new JSONSerializer(out);
            for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
                serializer.config(feature, true);
            }
            serializer.write(object);
            return out.toString();
        } finally {
            out.close();
        }
    }

演示程序

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
/**
 * 使用FastJson将实体对象转换成Json字符串测试类
 */
public class FastJsonApplication {
     public static void main(String[] args) {
        User user = new User();
        user.setId(1L);
        user.setUsername("张三");
        user.setPassword("");
        user.setMobile(null);
        user.setCountry("中国");
        user.setCity("武汉");
     String jsonUser = null;
        /**
         * 指定排除属性过滤器和包含属性过滤器
         * 指定排除属性过滤器:转换成JSON字符串时,排除哪些属性
         * 指定包含属性过滤器:转换成JSON字符串时,包含哪些属性
         */
        String[] excludeProperties = {"country", "city"};
        String[] includeProperties = {"id", "username", "mobile"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
        excludefilter.addExcludes(excludeProperties);
        PropertyPreFilters.MySimplePropertyPreFilter includefilter = filters.addFilter();
        includefilter.addIncludes(includeProperties);
        /**
         * 情况一:默认忽略值为null的属性
         */
        jsonUser = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat);
        System.out.println("情况一:\n" + jsonUser);
        /**
         * 情况二:包含值为null的属性
         */
        jsonUser = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        System.out.println("情况二:\n" + jsonUser);
        /**
         * 情况三:默认忽略值为null的属性,但是排除country和city这两个属性
         */
        jsonUser = JSONObject.toJSONString(user, excludefilter, SerializerFeature.PrettyFormat);
        System.out.println("情况三:\n" + jsonUser);
        /**
         * 情况四:包含值为null的属性,但是排除country和city这两个属性
         */
        jsonUser = JSONObject.toJSONString(user, excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        System.out.println("情况四:\n" + jsonUser);
        /**
         * 情况五:默认忽略值为null的属性,但是包含id、username和mobile这三个属性
         */
        jsonUser = JSONObject.toJSONString(user, includefilter, SerializerFeature.PrettyFormat);
        System.out.println("情况五:\n" + jsonUser);
        /**
         * 情况六:包含值为null的属性,但是包含id、username和mobile这三个属性
         */
        jsonUser = JSONObject.toJSONString(user, includefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        System.out.println("情况六:\n" + jsonUser);
    }
    /**
     * 用户实体类
     */
    public static class User {  
        private Long id;
        private String username;
        private String password;
        private String mobile;
        private String country;
        private String city;
    //此处省略了相应属性的set、get方法
}

运行结果:

结果说明:

  • 情况一和情况二说明了public static String toJSONString(Object object, SerializeFilter filter, SerializerFeature… features)这个方法将实体对象转换成JSON字符串时,默认是忽略掉值为null的属性,并且说明了如何使得转换后的JSON字符串包含值为null的属性。
  • 情况三和情况四说明了如何使用SerializeFilter来排除指定属性,使得转换后的JSON字符串中不包含这些属性。
  • 情况五和情况六说明了如何使用SerializeFilter来包含指定属性,使得转换后的JSON字符串中只包含这些属性。

JSONObject toJSONString 遇到的坑

引入pom文件

  <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
            <scope>test</scope>
        </dependency>

使用JSONObject 输出 int类型的map

是非json格式

import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
public class JsonTest {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "aaasa");
        map.put(2, "bbbbb");
        map.put(3, "ccccc");
        map.put(4, "ddddd");
        map.put(5, "eeeee");
        System.out.println(JSONObject.toJSONString(map));
    }
}

输出结果

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们