小编Rin*_*ang的帖子

Jackson ObjectMapper如何将byte []传递给String,如何在没有对象类的情况下将其翻译?

我想开发restful服务,它会将JSON String返回给客户端.现在我的对象中有byte []属性.

我使用ObjectMapper将此对象转换为json并响应客户端.但是如果我使用String.getBytes()来翻译接收到的字符串,我发现byte []是错误的.以下是示例.

Pojo课程

public class Pojo {
    private byte[] pic;
    private String id;
    //getter, setter,...etc
}
Run Code Online (Sandbox Code Playgroud)

准备数据:使用image获取字节数组

InputStream inputStream = FileUtils.openInputStream(new File("config/images.jpg"));
byte[] pic = IOUtils.toByteArray(inputStream);
Pojo pojo = new Pojo();
pojo.setId("1");
pojo.setPic(pic);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(pojo);
Run Code Online (Sandbox Code Playgroud)

--Situation 1:使用readvalue对象=> image2.jpg是正确的

Pojo tranPojo = mapper.readValue(json, Pojo.class);

byte[] tranPicPojo = tranPojo.getPic();
InputStream isPojo = new ByteArrayInputStream(tranPicPojo);
File tranFilePojo = new File("config/images2.png");
FileUtils.copyInputStreamToFile(isPojo, tranFilePojo);
Run Code Online (Sandbox Code Playgroud)

--Situation 2:使用readvalue来映射并得到String => image3.jpg被破坏了

Map<String, String> map = mapper.readValue(json, …
Run Code Online (Sandbox Code Playgroud)

java arrays json jackson objectmapper

5
推荐指数
2
解决办法
2万
查看次数

标签 统计

arrays ×1

jackson ×1

java ×1

json ×1

objectmapper ×1