【问题标题】:JsonMappingException: Can not construct instance of CommonsMultipartFileJsonMappingException:无法构造 CommonsMultipartFile 的实例
【发布时间】:2014-08-28 20:22:30
【问题描述】:

我正在使用 Spring-MVC 3.0,在我的应用程序中,我发送了一些带有多个附件的信息,每个文件都有标题、ID 等。所以,我制作了一个 DTO,如下所示

public class MyDTO {

Long id;

Integer age;

MultipartFile infoFile;

// getter setter

我只是根据我的JS文件中的上述DTO类创建一个JSON对象。

这是我的Controller 映射:

@RequestMapping(value = "/saveInfo", method = RequestMethod.POST)
public @ResponseBody String saveInfo(
       @RequestParam(value = "data", required = true) String stdData,
       @RequestParam(value = "fileData", required = false) MultipartFile[] files,
       HttpSession session,HttpServletRequest request) {
    
       MyDTO dto;
       try {
                dto = mapper.readValue(stdData, new TypeReference<MyDTO>() {});  
        } catch (JsonParseException e) {
                e.printStackTrace();
        } catch (JsonMappingException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }

但我收到以下错误:

org.codehaus.jackson.map.JsonMappingException: Can not construct instance of    org.springframework.web.multipart.commons.CommonsMultipartFile, 
problem: no suitable creator method found to deserialize from JSON String
at [Source: java.io.StringReader@19747c9; line: 1, column: 336] (through reference chain: com.avi.dto.MyDTO["hbvFile"])

【问题讨论】:

  • 它可能需要一个无参数构造函数,而CommonsMultipartFile 没有。
  • 您能展示一下您的JSON 的样子吗?

标签: java json spring-mvc jackson multipart


【解决方案1】:

其实我自己找到了答案。我们不能直接在 JSON 对象中发送文件。 File 对象不保存文件,它保存文件的路径,即。 C:/hi.txt。如果这就是我们在 JSON 中放入的内容,它将产生

{"File" : "C:/hi.txt"}

它不会包含文件内容。所以我们还不如直接放文件路径

JSONObject my_data = new JSONObject();
my_data.put("User", "Avi");
my_data.put("Date", "22-07-2013");
my_data.put("File", "C:/hi.txt");

如果您尝试使用 JSON 进行文件上传,一种方法是使用 Java 7 的 NIO 从文件中读取字节

byte[] bytes = Files.readAllBytes(file_upload .toPath());

Base64 对这些字节进行编码,并将它们作为字符串写入 JSONObject。使用 Apache Commons 编解码器

Base64.encodeBase64(bytes);
my_data.put("File", new String(bytes));

94 Unicode 字符可以根据 JSON 规范表示为一个字节(如果您的 JSON 以 UTF-8 传输)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2016-07-09
    • 1970-01-01
    • 2012-09-26
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多