java – 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
}

准备数据:使用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);

–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);

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

Map<String, String> map = mapper.readValue(json, Map.class);

byte[] tranString = map.get("pic").getBytes();
InputStream isString = new ByteArrayInputStream(tranString);
File tranFileString = new File("config/images3.png");
FileUtils.copyInputStreamToFile(isString, tranFileString);

如果我必须使用情境2来翻译JSON字符串,我该怎么办?因为客户端无法获取Pojo.class,所以客户端只能自己翻译JSON字符串.

非常感谢!

最佳答案:

Jackson正在将byte []序列化为Base64字符串,如the documentation of the serializer所述.

默认的base64变体是MIME without line feed(一行中的所有内容).

您可以使用ObjectMapper上的setBae64Varient更改变体.

上一篇:json字符串与java对象的相互转换(jackson)


下一篇:mybatis(Controller返回JSON数据(集合、日期、日期工具类))