SpringBoot 中使用HttpMessageConverters做Json转换

依赖

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>

SpringBoot启动类中配置转换器

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1、创建FastJson信息转换对象 
        FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
        //2、创建FastJsonConfig对象并设定序列化规则  序列化规则详见SerializerFeature类中,后面会讲
        FastJsonConfig fastJsonConfig= new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.WriteNonStringKeyAsString);
        //本人就坑在WriteNonStringKeyAsString 将不是String类型的key转换成String类型,否则前台无法将Json字符串转换成Json对象
      
        //3、中文乱码解决方案
        List<MediaType> fastMedisTypes = new ArrayList<MediaType>();
        fastMedisTypes.add(MediaType.APPLICATION_JSON_UTF8);//设定Json格式且编码为utf-8
        fastConverter.setSupportedMediaTypes(fastMedisTypes);
        //4、将转换规则应用于转换对象 
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(fastConverter);
    }

Controller

    //初始化入库情况选项数据
    @ApiOperation("初始化入库情况选项数据")
    @RequestMapping(value = "init-stock-statu",method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    public ResultBean<?> initStockStatus(){
        Map<String, Map<Object, String>> partThree = new HashMap<>(3);

        //入库状态 下拉选框
        Map<Object, String> stockStatus = new HashMap<>(6);
        for (StockStatusEnum c : StockStatusEnum.values()) {
            stockStatus.put(c.getCode(), c.getDesc());
        }
        partThree.put("stockStatus", stockStatus);

        //入库类型 下拉选框
        Map<Object, String> stockType = new HashMap<>(6);
        for (StockTypeEnum c : StockTypeEnum.values()) {
            stockType.put(c.getCode(), c.getDesc());
        }
        partThree.put("stockType", stockType);
        return new ResultBean<>(partThree);
    }

当访问controller的时候,就会将对象转化成Json字符串返回了

FastJson的SerializerFeature(序列化规则)

    public enum SerializerFeature {
        QuoteFieldNames,//输出key时是否使用双引号,默认为true 

        UseSingleQuotes,//使用单引号而不是双引号,默认为false

        WriteMapNullValue,//是否输出值为null的字段,默认为false 

        WriteEnumUsingToString,//Enum输出name()或者original,默认为false

        UseISO8601DateFormat,//Date使用ISO8601格式输出,默认为false

        WriteNullListAsEmpty,//List字段如果为null,输出为[],而非null 

        WriteNullStringAsEmpty,//字符类型字段如果为null,输出为"",而非null 
     
        WriteNullNumberAsZero,//数值字段如果为null,输出为0,而非null 

        WriteNullBooleanAsFalse,//Boolean字段如果为null,输出为false,而非null

        SkipTransientField,//如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true

        SortField,//按字段名称排序后输出。默认为false

        @Deprecated
        WriteTabAsSpecial,//把\t做转义输出,默认为false

        PrettyFormat,//结果是否格式化,默认为false

        WriteClassName,//序列化时写入类型信息,默认为false。反序列化是需用到

        DisableCircularReferenceDetect,//消除对同一对象循环引用的问题,默认为false

        WriteSlashAsSpecial,//对斜杠'/'进行转义

        BrowserCompatible,//将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false

        WriteDateUseDateFormat,//全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);

        NotWriteRootClassName,//暂不知,求告知

        DisableCheckSpecialChar,//一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false 

        BeanToArray; //暂不知,求告知


        private SerializerFeature(){
              mask = (1 << ordinal());
        }

        private final int mask;

        public final int getMask() {
            return mask;
        }

        public static boolean isEnabled(int features, SerializerFeature feature) {
              return (features & feature.getMask()) != 0;
        }

        public static int config(int features, SerializerFeature feature, boolean state) {
            if (state) {
                features |= feature.getMask();
            } else {
                features &= ~feature.getMask();
            }

          return features;
      }
  }

 

6人点赞

 

SpringBoot

 



作者:LeonardoEzio
链接:https://www.jianshu.com/p/d209c02f840f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个基于 Spring 的轻量级框架,可以快速搭建基于 Spring 的应用程序。而 Fastjson 是一个高性能的 Java 序列化和反序列化库,可以处理复杂的 JSON 数据。 如果想要在 Spring Boot 自定义 Fastjson 作为 JSON 消息转换器,可以按照以下步骤进行操作: 首先,在 pom.xml 文件引入 Fastjson 的依赖,可以通过以下代码来添加依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> ``` 然后,在 Spring Boot 的配置类中配置 Fastjson 作为 JSON 消息转换器。可以通过以下代码来实现: ```java @Configuration public class FastjsonConfig { @Bean public HttpMessageConverters fastjsonHttpMessageConverter() { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setDefaultCharset(Charset.forName("UTF-8")); List<MediaType> supportedMediaTypes = new ArrayList<>(); supportedMediaTypes.add(MediaType.APPLICATION_JSON); converter.setSupportedMediaTypes(supportedMediaTypes); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.PrettyFormat); converter.setFastJsonConfig(config); return new HttpMessageConverters(converter); } } ``` 最后,在 Spring Boot 的主类中加上 @EnableWebMvc 注解,启用自定义的 JSON 消息转换器。 通过以上步骤,就成功地使用了 Spring Boot 自定义 Fastjson 作为 JSON 消息转换器。这样可以方便地处理 JSON 数据,提升了系统的性能和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值