【发布时间】:2020-01-14 08:27:35
【问题描述】:
如何以邮递员 json 格式发送 base64 图像。我在邮递员表单数据中添加了图像文件,它以 json 格式编码详细信息,但仅在我的尝试中我收到了一个错误的请求。 [JSON 解析错误:无法从 START_OBJECT 令牌中反序列化 byte[] 的实例]。发现源中没有错误,但postman中json格式的实际问题。消息来源:https://github.com/arun0009/ocr-tess4j-rest
我应用了堆栈溢出解决方案,但它重复了相同的错误。我从堆栈溢出建议类型中以 json 格式添加 []、{}。
类:
public class Image {
private String id;
private String userId;
private byte[] image;
private String extension;
private String text; }
控制器:
@RequestMapping(value = "ocr/v1/upload", method= RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Status doOcr(@RequestBody Image image) throws Exception {
try { ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(image.getImage()));
Tesseract tesseract = new Tesseract(); // JNA Interface Mapping
String imageText = tesseract.doOCR(ImageIO.read(bis));
image.setText(imageText);
repository.save(image);
LOGGER.debug("OCR Result = " + imageText);
} catch (Exception e) {
LOGGER.error("TessearctException while converting/uploading image: ", e);
throw new TesseractException(); }
测试用例:
@Test
public void testDoOcr() throws IOException {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", MediaType.APPLICATION_JSON_VALUE);
headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);
Image image = new Image();
InputStream inputStream=lassLoader.getSystemResourceAsStream("eurotext.png");
image.setUserId("arun0009");
image.setExtension(".png");
image.setImage(Base64.encodeBase64(IOUtils.toByteArray(inputStream)));
String response=given().contentType("application/json").headers(headers) .body(image).when().post("http://localhost:8080/ocr/v1/upload").then()
.statusCode(200).extract().response().body().asString(); System.out.println(response); }
JSON:
{ "image": {
"userId": "arun0009",
"extension": ".png",
"text": "iVBORw0KGgoA"
}
JSON 解析错误:
无法从 START_OBJECT 令牌中反序列化
byte[]的实例;嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance ofbyte[]out of START_OBJECT token\n at [Source: (PushbackInputStream);
【问题讨论】:
标签: json spring-boot base64 postman tess4j