邮递员json格式存在问题。我想发布一个带有编码图像的图像,以将其存储在mongodb实例中。但是我收到一个错误400。我已将图像附加在formdata中,并且它以json格式编码了详细信息。但是我仍然得到相同的400错误重复
模型类
public class Image {
@Id
private String id;
private String userId;
private byte[] image;
private String extension;
private String text;
} /with getters and setter and constructors
CONTROLLER
@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();
}
return new Status("success"); }
JSON:
{
"image": {
"userId": "arun0009",
"extension": ".png",
"text": "WlgSmI3XGrnq31Uy6Vfnuo/qnHz1K8Z1+e4flJXk"
}
}
代码:
@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 = ClassLoader.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);
}
“状态”:400, “错误”:“错误请求”, “ message”:“ JSON解析错误:无法从START_ARRAY令牌中反序列化
com.tess4j.rest.model.Image
的实例;嵌套的异常是com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从START_ARRAY中反序列化com.tess4j.rest.model.Image
的实例\ n在[来源:(PushbackInputStream);第1行,第1列]中标记“, “ path”:“ / ocr / v1 / upload”
答案 0 :(得分:0)
好吧,我真的认为您的问题与转换有关。尝试使用类似的注释来忽略您未在JSON中传递的字段:
@JsonIgnore
@JsonProperty(value = "user_password")
public String userPassword;
参考文献:Ignore fields from Java object dynamically while sending as JSON from Spring MVC。
编辑
您的Image类可以具有“私有字符串imageReceived”(Base64String)和“私有字节[] image”。您可能会收到一个字符串,然后解密为byte []。 HTTP事务只能通过您已经转换的方式传递字符串值,您只需要在Web API中接收此字符串值