简体   繁体   中英

How to receive a non-entity class as param on POST method?

Controller method:

@PostMapping("/nova")
@ResponseStatus(HttpStatus.CREATED)
public String adicionarTemp(@RequestBody TempCaptacao temp) {

Param Class:

public class TempCaptacao{
    String dsNome;
    ...
    List<TempResponsavel> listaResponsavel;
public TempCaptacao() {

        }

SubParam Class:

public class TempResponsavel{
        Long id;
        String dsNome;
...
public TempResponsavel() {

        }

When Angular calls this method, passing a JSON (as below) my springs returns this error:

.wsmsDefaultHandlerExceptionResolver: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of com.spin.spincare.controller.MovAtendimentoCaptacaoController$TempCaptacao (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.spin.spincare.controller.MovAtendimentoCaptacaoController$TempCaptacao (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor at [Source: (PushbackInputStream); line: 1, column: 2]]

JSON:

{ 
   "dsNome":"teste",
   "dsGenero":"Masculino",
   "dtNascimento":"2000-12-30T02:00:00.000Z",
   "idConvenio":16,
   "dsCep":"12321321",
   "dsEndereco":"teste",
   "dsEstado":"SC",
   "dsCidade":"",
   "dsBairro":"",
   "dsComplemento":"",
   "listaResponsavel":[ 
      { 
         "id":1,
         "dsNome":"teste",
         "nrCelular":"231321312213",
         "dsEmail":"",
         "dsGrau":"Pai"
      }
   ]
}

I've those empty constructor methods, but with a list inside my class, how can I pass this class as param to my POST method?

EDIT

Missing static definition on my TempCaptacao class.. Thanks!

After thinking about the error and what you have posted, I think what you are doing is this:

public class TempCaptacao {
    // attributes etc
    public TempCaptacao() {}
    public class TempResponsavel { // inner class
        // attributes etc
        public class TempResponsavel() {}
    }
}

Don't do that. Define the classes in your model separately, if for no other reasons than maintainability / readability / extendability.

I think JSON should be able to deserialize this if you remove the constructor from your inner class, but you're going to experience any number of issues doing something nonstandard like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM