Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
Use interface in Spring controller method argument

I've two classes A & B which are implementing an interface.

public class A implements MyInterface {

    // Class A stuff
  private String name;

  public String getName() {
   return name;
  }

  public void setName(String name) {
this.name = name;
 }
}

public class B implements MyInterface { 
    //Class B stuff

   private MyCustomClass myCustomclass;

   public String getName() {
    this.myCustomclass.getName();
 }
}


public interface MyInterface {

  public String getName();
}

I want to use a single controller method which can work on both A and B depending on which object the frontend sends. So when I try to use Interface, Spring complains no suitable message converter found.

@RequestMapping(value = "/mymethod", method = RequestMethod.POST) 
public String updateRecord(@RequestBody MyInterface myInterface, HttpServletResponse response) { 
        //Do stuff
}
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Jackson can determine which implementation is to use to serialize to JSON but it can't determine which to use to deserialize the JSON. For serializing, all it needs to do is call getClass() and build a serializer for that type. But there is (currently) no such type information when deserializing. You should use the Jackson annotations @JsonTypeInfo and @JsonSubTypes to achieve polymorphic json.

@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = A.class, name = "A"),
        @JsonSubTypes.Type(value = B.class, name = "B")})
public interface MyInterface {

}

Then the request body myInterface must be,

{type:'A', name:'My name'} or {type:'B', myCustomclass:{....}}

Refer these three :

Spring MVC @RequestBody into an Interface instead of a class

https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

Spring @RequestBody containing a list of different types (but same interface)

about 4 years ago · Santiago Trujillo Relatório

0

Have you tried by passing Object class or by passing generic type reference?

public String updateRecord(@RequestBody Object obj,..

or

public String updateRecord(@RequestBody T obj,.. // I am not sure for this

Then check instanceOf in your controller method.

about 4 years ago · Santiago Trujillo Relatório

0

As per my understanding spring/jackson will not be able to recognise what type of object to create unless incoming json explicitly mentions about the same. See below link, it talks about abstract classes though. Basically there are multiple ways to achieve this, using jsonTypeinfo or argument resolvers etc. Check if this helps. Abstract classes and Spring MVC @ModelAttribute/@RequestParam

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda