0

This is the same questions than :

Jackson JSON library: how to instantiate a class that contains abstract fields

Nevertheless its solution is not possible since my abstract class is in another project than the concrete one.

Is there a way then ?

EDIT

My architecture is as follows:

public class UserDTO {

    ...
    private LanguageDTO lang;

}

I send that object user :

restTemplate.postForObject(this.getHttpCore().trim() + "admin/user/save/1/" + idUser, userEntity, UserDTO.class);

Then I am supposed to receive it in the function :

 @RequestMapping(value = "/save/{admin}/{idUser}", method = RequestMethod.POST)
    public String saveUserById(@RequestBody final UserEntity user, @PathVariable Integer idUser, @PathVariable boolean admin)

with UserEntity defined as :

public class UserEntity extends AbstractUserEntity {
    ...

}

public abstract class AbstractUserEntity {

    ...
    private AbstractLanguageEntity lang;
}

I would like to know how I can specify that lang should be instantiate as LanguageEntity whereas abstract classes are in another project.

Community
  • 1
  • 1

3 Answers3

0

This could work assuming you can configure how the object get serialized. See the example here. Look under "1.1. Global default typing" to set the defaults to include extra information in your JSON string, basically the concrete Java type that must be used when deserializing.

Since it seems you need to do this for your Spring servlet, you would have to pass a Spring message converter as mentioned here

Then inside your custom objectMapper, you can do the necessary configuration:

public class JSONMapper extends ObjectMapper {    
    public JSONMapper() {
        this.enableDefaultTyping();
    }    
}

You could probably also make it work with Mix-ins, which allow you to add annotations to classes already defined. You can see and example here. This will also need to be configured inside the objectMapper.

If you need the same functionality on your client side (REST template), you can pass the object mapper as shown here.

Community
  • 1
  • 1
Andres Olarte
  • 4,380
  • 3
  • 24
  • 45
0

The easiest way to solve that issue is to add getters et setters in UserEntity but specifying a concrete class :

public LanguageEntity getLang() {
   return (LanguageEntity) lang;
}

public void setLang(LanguageEntity language){
   this.lang = language
}
0

If all that you want to achieve is to note that LanguageEntity is the implementation of AbstractLanguageEntity, you can register this mapping via module:

SimpleModule myModule = new SimpleModule())
  .addAbstractTypeMapping(AbstractLanguageEntity.class,
    LanguageEntity.class);
ObjectMapper mapper = new ObjectMapper()
   .registerMdoule(myModule);
StaxMan
  • 113,358
  • 34
  • 211
  • 239