JsonMappingException: Can not construct instance of

Jim C

I have an entity with two columns refering same column in other table. Basically, a Transaction depends on Account: when creating a new transaction a send money from one account to another.

Account:

@Entity
@Table(name = "accounts")
public class Account implements java.io.Serializable {

    private static final long serialVersionUID = 2612578813518671670L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idaccount", unique = true, nullable = false)
    private Long idaccount;

    @Column(name = "name", length = 50)
    private String name;

    @NotNull
    @ManyToOne
    @JoinColumn(name = "iduser")
    private User user;

...

Transaction:

@Entity
@Table(name = "transactions")
public class Transaction {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idtransaction", unique = true, nullable = false)
    private Long idtransaction;

    private BigDecimal amount;

    @NotNull
    @ManyToOne
    @JoinColumn(name = "SOURCE_ACCOUNT")
    private Account sourceAccount;

    @NotNull
    @ManyToOne
    @JoinColumn(name = "TARGET_ACCOUNT")
    private Account targetAccount;

...

TransactionController

@CrossOrigin
@RestController
@RequestMapping("/transaction")
public class TransactionController {

    @Autowired
    TransactionService transactionService;

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<Transaction> addTransaction(@RequestBody Transaction Transaction) {
        transactionService.save(Transaction);

        return new ResponseEntity<Transaction>(Transaction, HttpStatus.CREATED);
    }

...

If I try post to create a transaction (naturally I have the accounts already created):

{
"amount": 111,
"sourceAccount": 1,
"targetAccount": 2
}

I get:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of com.mycompany.basicbank.model.Account: no int/Int-argument constructor/factory method to deserialize from Number value (1)
 at [Source: java.io.PushbackInputStream@63447acf; line: 3, column: 18] (through reference chain: com.mycompany.basicbank.model.Transaction["sourceAccount"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.mycompany.basicbank.model.Account: no int/Int-argument constructor/factory method to deserialize from Number value (1)
 at [Source: java.io.PushbackInputStream@63447acf; line: 3, column: 18] (through reference chain: com.mycompany.basicbank.model.Transaction["sourceAccount"])

So my question is: what should I check in order to fix "Can not construct instance of com.livingit.basicbank.model.Account: no int/Int-argument constructor/factory method to deserialize from Number"?

pvpkiran

The problem is the json you are sending doesn't exactly match the Transaction class. hence you see the error.
But what you are trying to achieve is a valid scenario and can be done.

Some options.

  1. Create a new class(not Transaction) which matches the json. Like

    class TransactionClient {
       BigDecimal amount,
       Long sourceAccount,
       Long targetAccount
    }
    

And in the backend(controller or some in service) you can get the Acccounts from database with this sourceAccount and targetAccount and create a transaction object with this objects and save.

  1. From the frontend call backend to get the Accounts(json) for these source and target accounts and then call your transaction endpoint with the json like this

    {
      "amount": 111,
      "sourceAccount":  {
        "idaccount" :123123,
         ..... // All the Non Null fields
       },
      "targetAccount": {
        "idaccount" :45554,
         ..... // All the Non Null fields
       },
     }
    

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Can not construct instance of java.util.LinkedHashMap: no String-argument constructor/factory

JSON parse error: Can not construct instance of class

JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token

Convert JSON to Object throws JsonMappingException "Can not deserialize instance of class out of START_ARRAY token"

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of : poja class no suitable constructor found

Cannot construct instance of - Jackson

Jackson: InvalidFormatException: Can not construct instance of java.util.Date from String value

jackson throw JsonMappingException can not construct instance of

Jackson JsonMappingException: Can not deserialize instance

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of org.springframework.data.domain.Sort out of START_ARRAY token

Exception: "org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token"

JSON: InvalidFormatException: Can not construct instance of int from String value

Can not construct instance of IntentResponse, The validated object is null

Can C++ aggregate initialization be used to construct an instance of a class which implements an interface?

Can't understand JsonMappingException

JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token 1

ObjectMapper throws JsonMappingException when it try to construct instance with null field

JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)

Json and abstract class 'Can not construct instance'

JsonMappingException: Can not deserialize instance of java.util.List out of START_OBJECT token

Jackson with Generics JSON Can not construct instance of java.lang.Class

jsonMappingException org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at

Overcome "Can not construct instance of InterfaceClass" without hinting the parent

Jackson JSON Can not construct instance of "About" : deserialize issue

AWS Lex receives Invalid Response from lambda function - Can not construct instance of IntentResponse

Can I use willSet to construct a class instance dictionary entry?

How to construct class instance with super?

With Microsoft.Extensions.DependencyInjection, can I resolve the type and construct an instance while providing extra constructor parameters?

Pandas can not construct index

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive