JSON字符串与JSON对象的转换
2025年4月13日小于 1 分钟
JSON字符串与JSON对象的转换
- 后端如果接收的参数为JSON字符串,此时又要进行对象的属性拷贝(对象与对象之间)。
- 就先要把接收到的JSON字符串转化为JSON对象才能进行对象的属性拷贝。
常见场景
- 在接口要同时接收文件类型和对象参数时,解决方案之一就是把对象参数用字符串来接收,之后再进行转换。
接收的JSON字符串
@PostMapping("/upload")
public Result<String> upload(@RequestPart MultipartFile file,@RequestParam String pictureDto) {
return pictureService.upload(file, pictureDto);
}
类型转换
@Override
public Result<String> upload(MultipartFile file, String pictureDtoJsonStr) {
if (file.isEmpty()) {
throw new CustomerException(PARAMS_ERROR, "上传文件不能为空");
}
//把接收到的json对象字符串,转化为json对象
PictureDto pictureDto = JSONUtil.toBean(pictureDtoJsonStr, PictureDto.class);
//对象拷贝
Picture picture = new Picture();
BeanUtils.copyProperties(pictureDto, picture);
}