栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

解决fastjson从1.1.41升级到1.2.28后报错问题详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决fastjson从1.1.41升级到1.2.28后报错问题详解

最近因为fastjson安全漏洞,升级jar包时,踩了一些坑。

新版本FastJsonHttpMessageConverter初始化,默认设置MediaType为** }

后续在org.springframework.http.converter.AbstractHttpMessageConverter.write过程中,又要判断Content-Type不能含有通配符,这应该是一种保护机制,并强制用户自己配置MediaType。代码如下:

  @Override
  public final void write(final T t, MediaType contentType, HttpOutputMessage outputMessage)
      throws IOException, HttpMessageNotWritableException {
    final HttpHeaders headers = outputMessage.getHeaders();
    if (headers.getContentType() == null) {
      MediaType contentTypeToUse = contentType;
      if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
 contentTypeToUse = getDefaultContentType(t);
      }
      if (contentTypeToUse != null) {
      //设置Content-Type,不允许含有通配符
 headers.setContentType(contentTypeToUse);
      }
    }
    ......
    if (outputMessage instanceof StreamingHttpOutputMessage) {
      ......
    }else {
    //自定义MessageConverter的write操作
      writeInternal(t, outputMessage);
      outputMessage.getBody().flush();
    }
  }
  public void setContentType(MediaType mediaType) {
    Assert.isTrue(!mediaType.isWildcardType(), "'Content-Type' cannot contain wildcard type '*'");
    Assert.isTrue(!mediaType.isWildcardSubtype(), "'Content-Type' cannot contain wildcard subtype '*'");
    set(CONTENT_TYPE, mediaType.toString());
  }

所以,需要为ViewAwareJsonMessageConverter设置supportedMediaTypes:


  
    
      application/json;charset=UTF-8
      application/*+json;charset=UTF-8
    
  
新版本序列化默认不再对字段进行排序

这个是一个签名算法的场景:客户端对参数进行序列化,然后md5加密成一个签名;服务端按照相同的算法解析一遍参数,对比签名值。这里加密依赖json序列化之后的字符串,也就依赖序列化时字段的排序。

这是fastjson做了一个性能优化,将排序需求抽象出一个SerializerFeature,供用户自己配置。如果需要排序场景,在序列化时添加参数SerializerFeature.MapSortField即可,即:

JSON.toJSonString(obj, SerializerFeature.MapSortField);

官方文档

1.2.3之后的版本,Map的序列化没有做排序再输出,原因是通过TreeMap排序很影响性能。

1.2.27版本中增加SerializerFeature.MapSortField实现同样的功能。

使用方法如下:

a) 传入SerializerFeature.MapSortField参数。 JSON.toJSonString(map, SerializerFeature.MapSortField);

b) 通过代码修改全局缺省配置。 JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.MapSortField.getMask();

c) 通过JVM启动参数配置修改全局配置 -Dfastjson.serializerFeatures.MapSortField=true

d) 通过类路径下的fastjson.properties来配置 fastjson.serializerFeatures.MapSortField=true

新老版本序列化和反序列化不兼容,会出乱码。

更多关于fastjson的相关文章请点击下面的相关链接

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135275.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号