Spring boot Jackson JSON解析错误:没有int/ int参数构造器/工厂方法来反序列化Number



My Connections实体模型是这样的

@Entity
@Getter@Setter@AllArgsConstructor@NoArgsConstructor
public class Connections implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private MyUsers receiver;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private MyUsers sender;
private boolean accepted
private boolean following;
}

我的MyUsers Model实体类看起来像这样

@Entity
@Getter @Setter @NoArgsConstructor @AllArgsConstructor
@Table(name = "my_users")
public class MyUsers implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private Long id;
@Column(nullable = false, unique = true)
private String userName;
private String password;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "myUsers", cascade = CascadeType.ALL)
@JsonIgnore
private List<Blogs> blogs;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
@JsonIgnore
private List<Connections> connections;
}

JSON POST请求体到连接API看起来像这样,

{
"receiver": 1,
"sender": 2,
"following": 1,
"accepted": 1
}

当我请求时,我得到这个错误

{
"timestamp": "2022-07-18T17:24:47.330+00:00",
"status": 400,
"error": "Bad Request",
"trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `me.protik.simplyblog.models.MyUsers` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (9); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `me.protik.simplyblog.models.MyUsers` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (9)n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 2, column: 17] (through reference chain: me.protik.simplyblog.models.Connections["receiver"])ntat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:391)ntat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:343)ntat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:185)ntat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:160)ntat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:133)ntat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122)ntat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179)ntat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146)ntat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)ntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)ntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)ntat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)ntat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)ntat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)ntat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)ntat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)ntat javax.servlet.http.HttpServlet.service(HttpServlet.java:681)ntat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)ntat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)ntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)ntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)ntat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)ntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)ntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:111)ntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)ntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)ntat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)ntat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122)ntat org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)ntat org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat me.protik.simplyblog.auth.filters.JwtRequestFilter.doFilterInternal(JwtRequestFilter.java:50)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)ntat org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)ntat org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112)ntat org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)ntat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)ntat org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)ntat org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)ntat org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354)ntat org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267)ntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)ntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)ntat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)ntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)ntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)ntat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)ntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)ntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)ntat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)ntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)ntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)ntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)ntat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)ntat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)ntat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)ntat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)ntat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)ntat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)ntat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)ntat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)ntat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)ntat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)ntat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1787)ntat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)ntat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)ntat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)ntat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)ntat java.base/java.lang.Thread.run(Thread.java:833)nCaused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `me.protik.simplyblog.models.MyUsers` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (9)n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 2, column: 17] (through reference chain: me.protik.simplyblog.models.Connections["receiver"])ntat com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)ntat com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1728)ntat com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1353)ntat com.fasterxml.jackson.databind.deser.ValueInstantiator.createFromInt(ValueInstantiator.java:324)ntat com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromInt(StdValueInstantiator.java:376)ntat com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromNumber(BeanDeserializerBase.java:1442)ntat com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:198)ntat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:186)ntat com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)ntat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:391)ntat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:184)ntat com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:323)ntat com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4674)ntat com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3682)ntat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:380)nt... 95 moren",
"message": "JSON parse error: Cannot construct instance of `me.protik.simplyblog.models.MyUsers` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (9); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `me.protik.simplyblog.models.MyUsers` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (9)n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 2, column: 17] (through reference chain: me.protik.simplyblog.models.Connections["receiver"])",
"path": "/user/connections/add"
}

只有当我从JSON中删除发送方和接收方时,API才能工作。

我所有的实体类都包含Lombok中的getter, setter和构造函数,并且user_id 1和2的用户实例存在于我的MySQL db

发送:用{receiver: {id: 1}}代替{receiver: 1},这将只使用id创建用户,而不会破坏其余的

在你的JSON中你正在发送一个数字

"receiver": 1,

但是在你的实体类中你期望对象

private MyUsers receiver;

无法将1反序列化为复杂对象。

如果12是数据库中的id,并且您希望这将神奇地反序列化-这不是它的工作方式

我正在回答我自己的问题,因为我刚刚找到了一个解决方案,虽然远非理想的设计,但它只是目前有效。

我添加了一个额外的类与其他模型类没有注释与@Entity(因此JPA和Hibernate与它无关)并调用它ConnectionsWrapper(我不太懂命名约定:|)

@Getter@Setter@AllArgsConstructor@NoArgsConstructor
public class ConnectionsWrapper implements Serializable {
private Long receiver;
private Long sender;
private boolean accepted;
private boolean following;
}

然后在控制器的添加/修改连接API我只是解析ConnectionWrapper类模型类型JSON使用@RequestBody然后创建一个新的原始Connections使用ConnectionWrapper类型的JSON请求体中的信息设置数据,然后通过Service和Repository函数将新的连接类型对象保存在数据库中。

@PostMapping("/user/connections/add")
public void addModConnection(@RequestBody ConnectionsWrapper connectionsWrapper){
Connections connection = new Connections();
connection.setReceiver(myUsersService.showUserByIdService(connectionsWrapper.getReceiver()));
connection.setSender(myUsersService.showUserByIdService(connectionsWrapper.getSender()));
connection.setAccepted(connectionsWrapper.isAccepted());
connection.setFollowing(connection.isFollowing());
myUsersService.addModConnectionService(connection);
}

最新更新