JiuyeXD's Blog
九叶
九叶博主

越努力 越幸运

登录
夜间

RestTemplate文件上传请求FileSystemResource被FastJson序列化后变为0kb的问题

1. 问题

有个功能需要调用一个传输文件的api,使用FileSystemResource进行传输,在调用api之前使用JSONObject.toJSONString()输出一下log之后 发现每次输出log之后本地文件就会变成0KB

2. 分析

FileSystemResource 是spring封装的类,其实现了WritableResource接口

public class FileSystemResource extends AbstractResource implements WritableResource {...}

在递归解析字段时,由于是采用getter方式,getOutputStream被当做getter方法被调用,

public interface WritableResource extends Resource {
        // omit

	/**
	 * Return an {@link OutputStream} for the underlying resource,
	 * allowing to (over-)write its content.
	 * @throws IOException if the stream could not be opened
	 * @see #getInputStream()
	 */
	OutputStream getOutputStream() throws IOException;
}

getXX本意是获取XX字段的值,但getOutputStream()被调用,拿到output后未写入任何值,相当于向output写入了空,后被flush到磁盘导致的文件被重写了

3. 解决

  1. 不要toJsonString打印复杂对象,特别是不熟悉的class
  2. 避免使用FileSystemResource类,使用其他对象代替

4. 参考资料

https://github.com/alibaba/fastjson/issues/3436

https://github.com/alibaba/fastjson/issues/3547#issuecomment-728782084

THE END