首页 > 解决方案 > Spring Boot:无法构造……的实例:没有从数值 (1) 反序列化的 int/Int-argument 构造函数/工厂方法;

问题描述

我正在尝试使用 RestTemplate(Spring Boot)从休息服务读取响应但是当我在 Eclipse 中运行 tomcat 服务器时,我总是收到此错误:没有 int/Int-argument 构造函数/工厂方法从数值反序列化( 1);

spring boot REST API pom.xml 如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>

    <spring-framework.version>5.1.8.RELEASE</spring-framework.version>

   <jackson.version>2.9.9</jackson.version>
   <oauth2.version>2.3.4.RELEASE</oauth2.version>
</properties>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>${oauth2.version}</version>
</dependency>   
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.9</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.9</version>
</dependency>

我尝试使用以下方法构建其余 api:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

但它抛出了同样的错误。

我的 Spring Boot REST API 中有这两个类:

路由.java

@Entity

@Table(name = "ROUTE")

@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id", scope = Route.class)

public class Route implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator="native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "ID", updatable = false, nullable = false)
    private Long id = null;

    @Column(name = "ORIGIN", nullable = false)
    @NotEmpty(message = "*This field is required!")
    private String origin;

    @Column(name = "DESTINATION", nullable = false)
    @NotEmpty(message = "*This field is required!")
    private String destination;

    @Column(name = "STATUS", nullable = true)
    private String status;

    @Column(name = "DATE_CREATED", nullable = true)
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
    @Temporal(TemporalType.DATE)
    private Date dateCreated;

    @Column(name = "TOKEN", nullable = false)
    private String token;

    @Column(name = "SYNC_STATUS", nullable = false)
    private String syncStatus;

    /*@OneToMany(cascade = CascadeType.ALL, mappedBy = "route", fetch = FetchType.LAZY)
    @JsonBackReference(value = "trips")
    private Set<Trip> trips = new HashSet<>();*/

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="ROUTE_BRANCH_ID", referencedColumnName = "ID", nullable = false)
    //@JsonManagedReference
    private Branch branch;

    ...

}

Trip.java

@Entity

@Table(name = "TRIP")

@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id", scope = Trip.class, resolver = CustomObjectIdResolver.class)

public class Trip implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator="native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "ID", updatable = false, nullable = false)
    private Long id = null;

    @Column(name = "TRIP_NUMBER", nullable = false)
    @NotEmpty(message = "*This field is required!")
    private String tripNumber;

    @Column(name = "DEPARTURE_DATE", nullable = false)
    @Temporal(TemporalType.DATE)
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
    //@DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date departureDate;

    @Column(name = "DEPARTURE_TIME", nullable = false)
    @NotEmpty(message = "*This field is required!")
    private String departureTime;

    @Transient
    private int availableSeatsNo;

    @Column(name = "TRIP_FARE")
    private double tripFare;

    @Column(name = "TYPE", nullable = false)
    @NotEmpty(message = "*This field is required!")
    private String type;

    @Column(name = "STATUS", nullable = false)
    private String status;

    @Column(name = "DISPATCHED")
    private boolean dispatched;

    @Column(name = "LOADING_SEQUENCE", nullable = false)
    private String loadingSequence;

    @Column(name = "BRANCH_NAME", nullable = false)
    private String branchName;

    @Column(name = "TRANSPORT_INCOME")
    private double transportIncome;

    @Column(name = "TOTAL_INCOMES")
    private double totalIncomes;

    @Column(name = "TOTAL_EXPENSES")
    private double totalExpenses;

    @Column(name = "BALANCE")
    private double balance;

    @Column(name = "CHECKED_BY", nullable = true)
    private String checkedBy;

    @Column(name = "TOKEN", nullable = false)
    private String token;

    @Column(name = "SYNC_STATUS", nullable = false)
    private String syncStatus;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "trip", fetch =   FetchType.LAZY)
    @JsonBackReference(value = "ticketBookings")
    private Set<TicketBooking> ticketBookings = new HashSet<>();

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "trip", fetch = FetchType.LAZY)
    @JsonBackReference(value = "tripExpenses")
    private Set<TripExpense> tripExpenses = new HashSet<>();

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "trip", fetch = FetchType.LAZY)
    @JsonBackReference(value = "luggageIncomes")
    private Set<LuggageIncome> luggageIncomes = new HashSet<>();

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="TRI_VEHICLE_ID", referencedColumnName = "ID", nullable = false)
    //@JsonManagedReference
    private Vehicle vehicle;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="TRI_ROUTE_ID", referencedColumnName = "ID", nullable = false)
    //@JsonManagedReference
    private Route route;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="TRI_DRIVER_ID", referencedColumnName = "ID", nullable = false)
    //@JsonManagedReference
    private Driver driver;

    /*@ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="TRI_BRANCH_ID", referencedColumnName = "ID", nullable = false)
    //@JsonManagedReference
    private Branch branch;*/

    /*@ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="TRI_CURRENCY_ID", referencedColumnName = "ID", nullable = true)
    //@JsonManagedReference
    private Currency currency;*/

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="TRI_LEDGER_ACCOUNT_ID", referencedColumnName = "ID", nullable = false)
    //@JsonManagedReference
    private LedgerAccount ledgerAccount;

    ....

}

TripController.java

@RestController

@RequestMapping("/api/trip")

public class TripController {

    @Autowired
    private TripService resourceService;

    ...

    @RequestMapping(value="/dispatched-and-branch/{dispatched}/{branchName}", method = RequestMethod.GET)
    public ResponseEntity<?> getByDispatchedAndBranchName(@PathVariable("dispatched") boolean dispatched,   @PathVariable("branchName") String branchName) {

        List<Trip> resourceList = resourceService.getByDispatchedAndBranchName(dispatched, branchName);
        return new ResponseEntity<>(resourceList, HttpStatus.OK);
    }

...

}

我正在尝试使用 RestTemplate (Spring Boot) 读取来自其余服务的响应,如下所示:

@Component

public class ScheduledTasks {

    ....

    boolean dispatched = false;

    String branchName = "branchName";

    String dispatchedAndBranchUrl = "http://localhost:8089/primeerp-api/api/trip/dispatched-and-branch";

    Trip[] tripsArr = oauth2RestTemplate.getForObject(dispatchedAndBranchUrl + "/{dispatched}" + "/{branchName}", Trip[].class, dispatched, branchName);

    ...

}

我希望获得尚未在特定分支中分派的 Trip 对象的列表/数组,而是返回以下 RestClientException:

org.springframework.web.client.RestClientException: Error while extracting response for type [class [Lcom.fg.primeerp.model.Trip;] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.fg.primeerp.model.Route` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.fg.primeerp.model.Route` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)

    at [Source: (PushbackInputStream); line: 1, column: 4393] (through reference chain: java.lang.Object[][1]->com.fg.primeerp.model.Trip["route"])
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:117) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:737) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:311) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at com.fg.primeerp.scheduler.ScheduledTasks.createOrUpdateTrip2(ScheduledTasks.java:1735) ~[classes/:0.0.1-SNAPSHOT]
    at com.fg.primeerp.scheduler.ScheduledTasks$$FastClassBySpringCGLIB$$b2f2eb1e.invoke(<generated>) ~[classes/:0.0.1-SNAPSHOT]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at com.fg.primeerp.scheduler.ScheduledTasks$$EnhancerBySpringCGLIB$$652aa0ce.createOrUpdateTrip2(<generated>) ~[classes/:0.0.1-SNAPSHOT]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_144]
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_144]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_144]
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.fg.primeerp.model.Route` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.fg.primeerp.model.Route` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
 at [Source: (PushbackInputStream); line: 1, column: 4393] (through reference chain: java.lang.Object[][1]->com.fg.primeerp.model.Trip["route"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:245) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:102) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    ... 27 common frames omitted
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.fg.primeerp.model.Route` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
 at [Source: (PushbackInputStream); line: 1, column: 4393] (through reference chain: java.lang.Object[][1]->com.fg.primeerp.model.Trip["route"])
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1032) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.ValueInstantiator.createFromInt(ValueInstantiator.java:262) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromInt(StdValueInstantiator.java:356) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromNumber(BeanDeserializerBase.java:1324) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:173) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:369) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:195) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:21) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.9.jar:2.9.9]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3084) ~[jackson-databind-2.9.9.jar:2.9.9]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:239) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    ... 29 common frames omitted

我为解决这个问题所做的所有努力都被证明是徒劳的。请帮帮我。

标签: spring-boot

解决方案


推荐阅读