2

I am doing Spring Rest Api project with Spring 4.x

This Works:

Controller.java

@PostMapping("newTransaction")
TransactionRequestModel insertNewTransaction(@RequestBody TransactionRequestModel model){
    //do something
}

TransactionRequestModel.java

public class TransactionRequestModel {
    private int id;
    private List<KeyValue> keyValueList;
    public TransactionRequestModel(){}
    //default constructor
    //getter-setter 
}

KeyValue.java

public class KeyValue {

    String key;
    String value;
    //default constructor
    //setter-getter
}

Request Body Json

{
  "id": 1 
  "keyValueList": [
    {
      "key": "dummy",
      "value": "dummy"
    }
  ]
}

Spring message converter using jackson is working fine.

This Won't:

When i change TransactionRequestModel.java to following (and delete KeyValue.java)

public class TransactionRequestModel {

    public class KeyValue {     
      String key;
      String value;
      //default constructor
      //setter-getter
    }
    private int id;
    private List<KeyValue> keyValueList;
    public TransactionRequestModel(){}
    //default constructor
    //getter-setter 
}

means, making KeyValue an inner class, got following error.

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: No suitable constructor found for type [simple type, class com.example.model.TransactionRequestModel$KeyValue]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)

Why?

All the related post in SO mentions the first scenario. I would like to know why this wont work. Please help.

Ramanujan R
  • 1,292
  • 1
  • 13
  • 32

1 Answers1

7

You have to make your inner class static.

public class TransactionRequestModel {

  public static class KeyValue {     
    String key;
    String value;
    //default constructor
    //setter-getter
  }
  private int id;
  private List<KeyValue> keyValueList;
  public TransactionRequestModel(){}
  //default constructor
  //getter-setter 
}
Strelok
  • 46,161
  • 8
  • 92
  • 112