RestTemplate文件上传请求FileSystemResource被FastJson序列化后变为0kb的问题 [ 技术杂谈 ]
九叶的小窝 文章 正文
![As Long As You Love Me.](https://api.qwq.ro/storage/users/uid-1/1661304663.png)
九叶
{{nature("2022-04-19 13:42:44")}}更新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. 解决
- 不要toJsonString打印复杂对象,特别是不熟悉的class
- 避免使用
FileSystemResource
类,使用其他对象代替
4. 参考资料
https://github.com/alibaba/fastjson/issues/3436
https://github.com/alibaba/fastjson/issues/3547#issuecomment-728782084
{{nature('2021-12-07 15:29:00')}} {{format('2671')}}人已阅读
{{nature('2021-01-31 20:01:00')}} {{format('1172')}}人已阅读
{{nature('2020-12-11 21:17:00')}} {{format('1085')}}人已阅读
{{nature('2021-04-22 15:16:00')}} {{format('1057')}}人已阅读
目录
标签云
一言
评论 0
{{userInfo.data?.nickname}}
{{userInfo.data?.email}}