如何在Java spring rest 返回一个数组对象,在而不是字符串;

如何在Java spring rest 返回一个数组对象,在而不是字符串;,第1张

如何在Java spring rest 返回一个数组对象,在而不是字符串;

在spring mvc会将对象种的字节数组成员转换成base64编码的字符传格式,前台接收到数据后要进行base64界面才能恢复成原字节数组,网上有很多解决方案通过都修改produces = {"text/plain", "application/json"}为多媒体格式来解决;

public class ResponseByteArray {
    private String fileName;
    private byte[] file;
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public byte[] getFile() {
        return file;
    }
    public void setFile(byte[] file) {
        this.file = file;
    }   
}

@RequestMapping(value = "/getDataByte", method = RequestMethod.GET)
    public ResponseEntity uploadUImageGet() throws IOException {
        ResponseByteArray response = new ResponseByteArray();
        File fileImage = new File("D://images//download1.jpg");
        byte[] fileContent = Files.readAllBytes(fileImage.toPath());
        response.setFileName("testFile.jpg");
        response.setFile(fileContent);
        return new ResponseEntity(response, HttpStatus.OK);
    }
}

{ 
"fileName": "testFile.jpg", 
"file":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxIQEg8PEhIPFRIPDw8QEA8QDw8PEBAPFREWFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMsNygtLisBCgoKDg0NFQ8PFSsdFR0tLS0tKysrKy0tKy0tNy03LS0rKy0tLSsrKzc3LS0rLSsrKy0rKzctLTcrLSstNy0tK//AABEIAQMAwgMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAADAAECBAUGB//EAD8QAAIBAgMFBQUGBQIHAQAAAAECAAMRBCExBRJBUWEGMnGBkRMiUqHRFGJyscHwQpKisuEjkxUXM3OC0vEH/8QAGQEBAQEBAQEAAAAAAAAAAAAAAAECAwUE/8QAIBEBAQEAAwADAAMBAAAAAAAAABEBAgMSITFBEyJRB ... 
}

但是如果想将上边的json数据返回值变成如下格式该怎么办呢?

{ 
"fileName": "testFile.jpg", 
"file":[23,4,5,6,3,,7,45,6,5,34....]
}

其实对原方法稍作修改即可,这里用到了gson,可以在方法种显示的将对象转换为json字符串,不用spring MVC默认的转换方式即可。 

@RequestMapping(value = "/getDataByte", method = RequestMethod.GET)
public String uploadUImageGet() throws IOException {
   。。。

   return new Gson().toJson(responseDto);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5660784.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存