Ошибка синтаксического анализа JSON: невозможно создать экземпляр `com.tess4j.rest.model.Image` (хотя существует хотя бы один создатель): - PullRequest
0 голосов
/ 01 октября 2019

У меня ошибка анализа JSON

JSON parse error: Cannot construct instance of `com.tess4j.rest.model.Image` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.tess4j.rest.model.Image` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1')\n at [Source: (PushbackInputStream); line: 2, column: 8] (through reference chain: java.util.LinkedHashMap[\"id\"]) 

, и я не могу ее решить один раз.

CLASS:

public class Image {
    @Id   
    private String id;
    private String userId;
    @JsonProperty("image")
    private  byte[] image;
    private String extension;
    private String text;
//get & setters }

КОНТРОЛЛЕР:

 @RequestMapping(value = "ocr/v1/upload", method = RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public Status doOcr( @RequestBody Map<String, Image> image ) throws Exception {
try {
  ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(((Image) image).getImage()));
               Tesseract tesseract = new Tesseract(); // JNA Interface Mapping
                String imageText = tesseract.doOCR(ImageIO.read(bis));
                ((Image) 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");       }

 @RequestMapping(value = "ocr/v1/images/users/{userId}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public List<Image> getUserImages(@PathVariable String userId) throws Exception {
            List<Image> userImages = new ArrayList<>();
            try {
                userImages = repository.findByUserId(userId);
            } catch (Exception e) {
                LOGGER.error("Exception occurred finding image for userId: {} ", userId, e);
                throw new Exception();
            }            return userImages;        }

ДЕЛО ТЕСТА:

@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);
    }

    @Test
    public void testGetUserImages() 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);
        String response = given().contentType("application/json").headers(headers).when()
            .pathParam("userId", "arun0009").get("http://localhost:8080/ocr/v1/images/users/{userId}")
            .asString();
        System.out.println(response);
    }

JSON

{ 
    "id": "1",
    "userId": "arun0009",
    "extension": ".png",
    "text" : null,
    "image" : "ENCODE DETAILS OF IMAGe"
}

TRIED с другим форматом json и добавленной зависимостью json в сборке сборки, но та же ошибка повторяется. Невозможно решить.

image

1 Ответ

0 голосов
/ 01 октября 2019

Просто создайте пустой конструктор по умолчанию для класса Image, Джексон всегда запрашивает пустой.

public Image() 
}
...