Im learning Spring Boot and I made a demo but when I POST a request to add a Object it didn’t work!
The error message is:
{
"timestamp": 1516897619316,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)n at [Source: java.io.PushbackInputStream@1ff3f09a; line: 2, column: 9]",
"path": "/topics/"
}
My Entity:
public class Topic {
private String id;
private String name;
private String author;
private String desc;
public Topic(String id, String name, String author, String desc) {
this.id = id;
this.name = name;
this.author = author;
this.desc = desc;
}
//getters and setters
My controller:
public class TopicController {
@Autowired
private TopicService topicService;
@RequestMapping(value = "/topics", method = RequestMethod.POST)
public void addTopic(@RequestBody Topic topic) {
topicService.addTopic(topic);
}
My service:
@Service
public class TopicService {
private List<Topic> topics = new ArrayList<>(Arrays.asList(
new Topic("1", "topic1", "Martin", "T1"),
new Topic("2", "topic2", "Jessie", "T2")
));
public void addTopic(Topic topic) {
topics.add(topic);
}
}
My json:
{
"id": "3",
"name": "topic3",
"author": "Jessie3",
"desc": "T3"
}
Please Help !
Answer by Bradley McFarland
You need to annotate the constructor with @JsonCreator:,Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.,For deserialisation purposes Topic must have a zero-arg constructor.,NOTE: when annotating creator methods (constructors, factory methods), method must either be:
For example:
public class Topic {
private String id;
private String name;
private String author;
private String desc;
// for deserialisation
public Topic() {}
public Topic(String id, String name, String author, String desc) {
this.id = id;
this.name = name;
this.author = author;
this.desc = desc;
}
// getters and setters
}
Answer by Sawyer Knight
Hello, I am trying to use spring boot auto starter in my project. I am not sure what I am missing.
I am getting below error :,Below is my service class in spring boot application.,I get a very similar error, trying to use,Where MyClass has an Map<String,String> field, which I am trying to set to an empty Map via «{}»
@GraphQLApi
@Service
public class Serviceq {
@Autowired
PRepository pRepo;
@Transactional
@GraphQLQuery(name = "party")
public Test getPByNum(@GraphQLArgument(name = "num") String num)
throws Exception, ExecutionException {
Future<Test> test= partyRepo.findByNum(num);
return test.get();
}
}
Answer by Carly Landry
I have JSON parse error of ,Just create an empty constructor by default for Image class, Jackson asks always for empty one.,If you add any files,it will delete all existing files related to this question-(questions only answer remains unchanged),If no answers are exists it will remove immediately
I have JSON parse error of
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 }
CONTROLLER:
@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 CASE:
@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"
}
Answer by Marcus Boyle
Сообщение об ошибке:
{
"timestamp": 1516897619316,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)n at [Source: [email protected]; line: 2, column: 9]",
"path": "/topics/"
}
public class Topic {
private String id;
private String name;
private String author;
private String desc;
public Topic(String id, String name, String author, String desc) {
this.id = id;
this.name = name;
this.author = author;
this.desc = desc;
}
//getters and setters
public class TopicController {
@Autowired
private TopicService topicService;
@RequestMapping(value = "/topics", method = RequestMethod.POST)
public void addTopic(@RequestBody Topic topic) {
topicService.addTopic(topic);
}
@Service
public class TopicService {
private List<Topic> topics = new ArrayList<>(Arrays.asList(
new Topic("1", "topic1", "Martin", "T1"),
new Topic("2", "topic2", "Jessie", "T2")
));
public void addTopic(Topic topic) {
topics.add(topic);
}
}
Мой json:
{
"id": "3",
"name": "topic3",
"author": "Jessie3",
"desc": "T3"
}
Answer by Curtis Roberts
org.springframework.beans.factory.UnsatisfiedDependencyException: Erro ao criar bean com o nome ‘demoRestController’,Você precisa anotar o construtor com @JsonCreator :,/Erro de análise JSON: Não é possível construir a instância de io.starter.topic.Topic,Este é o comportamento padrão da biblioteca Jackson .
A mensagem de erro é:
{
"timestamp": 1516897619316,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of io.starter.topic.Topic: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)n at [Source: [email protected]; line: 2, column: 9]",
"path": "/topics/"
}
Minha Entidade:
public class Topic {
private String id;
private String name;
private String author;
private String desc;
public Topic(String id, String name, String author, String desc) {
this.id = id;
this.name = name;
this.author = author;
this.desc = desc;
}
//getters and setters
Meu controlador:
public class TopicController {
@Autowired
private TopicService topicService;
@RequestMapping(value = "/topics", method = RequestMethod.POST)
public void addTopic(@RequestBody Topic topic) {
topicService.addTopic(topic);
}
Meu serviço:
@Service
public class TopicService {
private List<Topic> topics = new ArrayList<>(Arrays.asList(
new Topic("1", "topic1", "Martin", "T1"),
new Topic("2", "topic2", "Jessie", "T2")
));
public void addTopic(Topic topic) {
topics.add(topic);
}
}
Meu json:
{
"id": "3",
"name": "topic3",
"author": "Jessie3",
"desc": "T3"
}
#java #json #spring #spring-boot #rest
Вопрос:
Когда я пытаюсь передать запрос json с помощью rest api почтальоном ,я сталкиваюсь с ошибкой, и вот ниже журнала ошибок, я хотел бы знать, что здесь не так, я подозреваю, что это проблема с конструкторами, знающими, что я написал конструктор всех параметров и конструктор по умолчанию, используя аннотации AllArgsConstructor и NoArgsConstructor, или что мне где-то не хватает аннотации, но я честно не уверен, где я ошибся.
2021-07-30 14:46:04.363 ERROR 7576 --- [nio-8080-exec-6] o.s.d.r.w.RepositoryRestExceptionHandler : JSON parse error: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/1'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/1')
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 5, column: 17] (through reference chain: org.sid.cinema.entities.Film["categorie"])
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/1'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/1')
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 5, column: 17] (through reference chain: org.sid.cinema.entities.Film["categorie"])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:389) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readInternal(AbstractJackson2HttpMessageConverter.java:350) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:199) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:246) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.lambda$read$6(PersistentEntityResourceHandlerMethodArgumentResolver.java:202) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at java.util.Optional.orElseGet(Optional.java:267) ~[na:1.8.0_191]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:202) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.resolveArgument(PersistentEntityResourceHandlerMethodArgumentResolver.java:132) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:170) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) [spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) [tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) [tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.48.jar:9.0.48]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.48.jar:9.0.48]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/1')
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 5, column: 17] (through reference chain: org.sid.cinema.entities.Film["categorie"])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1588) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1213) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromString(StdDeserializer.java:311) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1495) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:207) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:197) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:402) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:195) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:322) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4593) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3601) ~[jackson-databind-2.12.3.jar:2.12.3]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:378) ~[spring-web-5.3.8.jar:5.3.8]
... 54 common frames omitted
2021-07-30 14:46:04.415 WARN 7576 --- [nio-8080-exec-6] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/1'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/1')
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 5, column: 17] (through reference chain: org.sid.cinema.entities.Film["categorie"])]
2021-07-30 16:16:53.003 WARN 7576 --- [nio-8080-exec-2] tion$ResourceSupportHttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class org.springframework.data.rest.webmvc.PersistentEntityResource]]: java.lang.NullPointerException
2021-07-30 16:21:05.694 WARN 7576 --- [nio-8080-exec-8] tion$ResourceSupportHttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class org.springframework.data.rest.webmvc.PersistentEntityResource]]: java.lang.NullPointerException
2021-07-30 16:21:06.306 ERROR 7576 --- [nio-8080-exec-8] o.s.d.r.w.RepositoryRestExceptionHandler : JSON parse error: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/2'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/2')
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 5, column: 17] (through reference chain: org.sid.cinema.entities.Film["categorie"])
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/2'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/2')
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 5, column: 17] (through reference chain: org.sid.cinema.entities.Film["categorie"])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:389) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readInternal(AbstractJackson2HttpMessageConverter.java:350) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:199) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:246) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.lambda$read$6(PersistentEntityResourceHandlerMethodArgumentResolver.java:202) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at java.util.Optional.orElseGet(Optional.java:267) ~[na:1.8.0_191]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:202) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.resolveArgument(PersistentEntityResourceHandlerMethodArgumentResolver.java:132) ~[spring-data-rest-webmvc-3.5.2.jar:3.5.2]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:170) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) [spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) [tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) [tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) [tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.48.jar:9.0.48]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.48.jar:9.0.48]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.sid.cinema.entities.Categorie` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/categories/2')
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 5, column: 17] (through reference chain: org.sid.cinema.entities.Film["categorie"])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1588) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1213) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromString(StdDeserializer.java:311) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1495) ~[jackson-databind-2.12.3.jar:2.12.3]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:207) ~[jackson-databind-2.12.3.jar:2.12.3]
это то, что я написал в postman в качестве запроса json, используя этот URL: http://localhost:8080/films
используя метод post
{
"titre": "my titre8",
"description": "my descr8",
"realisateur": "realisateur8",
"categorie":"http://localhost:8080/categories/1"
}
вот класс по фильмам
package org.sid.cinema.entities;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Entity
@Data @AllArgsConstructor @NoArgsConstructor @ToString
public class Film {
@Id @GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String titre;
private String description;
private String realisateur;
private Date dateSortie;
private double duree;
private String photo;
@OneToMany(mappedBy="film")
private Collection<Projection> projections;
@ManyToOne
private Categorie categorie;
}
вот класс categorie
package org.sid.cinema.entities;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Entity
@Data @AllArgsConstructor @NoArgsConstructor @ToString
public class Categorie {
@Id @GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(length=75) // par defaut length=255
private String name ;
@OneToMany(mappedBy="categorie")
private Collection<Film> films;
}
Ответ №1:
Ваш запрос json пытается записать категорию как String
{
"titre": "my titre8",
"description": "my descr8",
"realisateur": "realisateur8",
"categorie":"http://localhost:8080/categories/1"
}
---
"categorie":"http://localhost:8080/categories/1"
Когда вы снимаете фильм, класс ожидает, что Катагори будет классом.
public class Film {
@Id @GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String titre;
private String description;
private String realisateur;
private Date dateSortie;
private double duree;
private String photo;
@OneToMany(mappedBy="film")
private Collection<Projection> projections;
@ManyToOne
private Categorie categorie;
}
Вы можете либо передать объект json в запросе json в форме Catagorie, либо добавить конструктор строковых аргументов, который он может использовать.
org.sid.cinema.entities.Categorie (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value
Создание конструктора, принимающего строку
public class Catagorie {
public Catagorie(String initStringUrl) {
// handle url
}
}
Комментарии:
1. Сэм Ороско я уже передаю объект json в запросе json ,я не понимаю , что это значит, форма категоризации формы, не знаю, как я добавляю конструктор строковых аргументов
2. Catagorie-это класс со множеством полей, вы пытаетесь передать его в виде строки. Вам нужно будет создать конструктор класса Catagorie, который принимает только строку, или вам нужно будет передать объект в объект запроса.
3. Сэм Ороско как я могу создать конструктор-это класс Catagorie, который принимает только строку, или как я могу передать объект в своем запросе
4. Вы отправляете запрос json объекта Film на свой сервер. Сервер не может десериализовать json, потому что вы отправляете поле catagorie в виде строки, которая в объекте File является объектом catagorie. Таким образом, сервер понятия не имеет, как десериализовать строку в объект. Сервер будет знать, как десериализоваться, если вы создадите конструктор, который принимает строку, а затем обработаете ее соответствующим образом или передадите объект json в запросе на фильм.
5. Сэм Ороско я понимаю проблему , но все еще не знаю, как создать конструктор, который принимает строку, можете ли вы показать мне это
Моя сущность
@Entity
@Table(name = "ARTICLES",schema = "NEWS_SCHEMA")
@Getter @Setter
@NoArgsConstructor
public class Article {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "TITLE")
private String title;
@Column(name = "CONTENT")
private byte[] content;
@ManyToOne
@JoinColumn(name = "CATEGORY_ID")
private Category categoryOfArticle;
@ManyToOne(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinColumn(name = "AUTHOR_ID" )
private Author authorOfArticle;
public Article(String title, Category categoryOfArticle, Author authorOfArticle) {
this.title = title;
this.categoryOfArticle = categoryOfArticle;
this.authorOfArticle = authorOfArticle;
}
}
Вторая :
@Entity
@Table(name = "AUTHORS", schema = "NEWS_SCHEMA")
@Getter
@Setter
@NoArgsConstructor
public class Author {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "NAME")
private String name;
@Column(name = "SURNAME")
private String surname;
@Column(name = "DATE_OF_BIRTH")
private Date dob;
@OneToMany(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
mappedBy = "authorOfArticle")
private List<Article> articlesOfAuthor;
public void addArticleToAuthor(Article article) {
if (articlesOfAuthor == null) {
articlesOfAuthor = new ArrayList<>();
}
articlesOfAuthor.add(article);
article.setAuthorOfArticle(this);
}
public Author(String name, String surname, Date dob) {
this.name = name;
this.surname = surname;
this.dob = dob;
}
}
Третья:
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "NAME")
private String name;
@OneToMany(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
mappedBy = "categoryOfArticle")
private List<Article> articlesInCategory;
public void addArticleInCategoriesList(Article article){
if (articlesInCategory == null){
articlesInCategory = new ArrayList<>();
}
articlesInCategory.add(article);
}
public Category(String name) {
this.name = name;
}
}
Метод контроллера:
@PostMapping("/articles")
public Article addNewArticle(@RequestBody Article article) {
articleService.saveArticle(article);
return article;
}
Метод контроллера обращается к сервису,который вызывает методы JpaRepository
Полный текст ошибки:
WARN 5768 --- [nio-8080-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver :
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot construct instance of `com.dataart.newsportal.entities.Author` (although at least one Creator exists):
no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/authors/7');
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.dataart.newsportal.entities.Author` (although at least one Creator exists):
no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/authors/7')<LF> at [Source:
(PushbackInputStream); line: 3, column: 20] (through reference chain: com.dataart.newsportal.entities.Article["authorOfArticle"])]
Is there some additional configuration required to get deserialization working with Spring’s RestTemplate
?
I’m getting the following error:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not construct instance of javax.money.MonetaryAmount: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of javax.money.MonetaryAmount: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: java.io.PushbackInputStream@2065cbae; line: 2, column: 13] (through reference chain: com.mypackage.PriceResource["price"])
I’m using version org.zalando:jackson-datatype-money:1.0.0-RC2
with 'org.javamoney:moneta:1.1'
and am trying to deserialize:
{ "price": { "amount": 1799.99, "currency": "USD" } }
into:
import javax.money.MonetaryAmount; import org.springframework.hateoas.ResourceSupport; public class PriceResource extends ResourceSupport { private MonetaryAmount price; public PriceResource() {} public MonetaryAmount getPrice() { return price; } public void setPrice(MonetaryAmount price) { this.price = price; } }
Using a RestTemplate
built as follows:
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); restTemplate.getMessageConverters().removeIf(messageConverter -> messageConverter.getClass() == MappingJackson2HttpMessageConverter.class); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter(objectMapper));
where the objectMapper
is created by SpringBoot (v1.5.7) and injected into the previous method and supplied the MoneyModule
via the following:
@Configuration class JacksonConfig { @Bean public MoneyModule moneyModule() { return new MoneyModule(); } }
To show that the RestTemplate
has an ObjectMapper
with the MoneyModule
, here’s the instance view in the debugger right after catching the above exception:
Note that I’ve also tried both of the following configs, as the README.md
wasn’t clear if was necessary or not, however both generated the same error as above:
@Configuration class JacksonConfig { @Bean public MoneyModule moneyModule() { return new MoneyModule().withMoney(); } }
@Configuration class JacksonConfig { @Bean public MoneyModule moneyModule() { return new MoneyModule().withMonetaryAmount(Money::of); } }