Rin*_*ang 5 java arrays json jackson objectmapper
我想开发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, Map.class);
byte[] tranString = map.get("pic").getBytes();
InputStream isString = new ByteArrayInputStream(tranString);
File tranFileString = new File("config/images3.png");
FileUtils.copyInputStreamToFile(isString, tranFileString);
Run Code Online (Sandbox Code Playgroud)
如果我必须使用情境2来翻译JSON字符串,我该怎么办?因为客户端无法获取Pojo.class,所以客户端只能自己翻译JSON字符串.
非常感谢!
Jackson 正在序列byte[]化为 Base64 字符串,如序列化程序文档中所述。
默认的 base64 变体是不带换行符的MIME(一行中的所有内容)。
您可以使用setBase64Variant上的来更改变体ObjectMapper。
ObjectMapper处理这个问题,通过单元测试表示:
@Test
public void byteArrayToAndFromJson() throws IOException {
final byte[] bytes = { 1, 2, 3, 4, 5 };
final ObjectMapper objectMapper = new ObjectMapper();
final byte[] jsoned = objectMapper.readValue(objectMapper.writeValueAsString(bytes), byte[].class);
assertArrayEquals(bytes, jsoned);
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这是杰克逊 2.x..
以下是如何使用 Jersey 将文件发送到浏览器:
@GET
@Path("/documentFile")
@Produces("image/jpg")
public Response getFile() {
final byte[] yourByteArray = ...;
final String yourFileName = ...;
return Response.ok(yourByteArray)
.header("Content-Disposition", "inline; filename=\"" + yourFilename + "\";")
.build();
Run Code Online (Sandbox Code Playgroud)
另一个例子,使用 Spring MVC:
@RequestMapping(method = RequestMethod.GET)
public void getFile(final HttpServletResponse response) {
final InputStream yourByteArrayAsStream = ...;
final String yourFileName = ...;
response.setContentType("image/jpg");
try {
output = response.getOutputStream();
IOUtils.copy(yourByteArrayAsStream, output);
} finally {
IOUtils.closeQuietly(yourByteArrayAsStream);
IOUtils.closeQuietly(output);
}
}
Run Code Online (Sandbox Code Playgroud)