Jarek
Jarek

Reputation: 110

Using spring converter in @RequestBody

Is it possible to enforce Converter ( org.springframework.core.convert.converter.Converter) to finish json object mapping?

Json code example:

{
 "name": "somename",
 "customObject": id
}

where somename - string, id - integer value

mapping to :

@Getter
@Setter
@NoArgConstructor
public class ParentObject{
    private String name;
    private CustomObject customObject; 
}

Converter code example:

@Component
public class CustomObjectConverter implements Converter<String, CustomObject>{

    @Autowired
    private CustomObjectService customObjectService;

    @Override
    public CustomObject convert(String arg0) {
        Long id = Long.parseLong(arg0);
        return customObjectService.findById(id);
    }   
}

What I want to achieve is to map that json to the object which will have automatically fetched from db nested object.

Upvotes: 5

Views: 7185

Answers (2)

I think there is a better way to solve this problem. All you need is to add one more implementation:

com.fasterxml.jackson.databind.util.Converter

And put an annotation over your object:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
...
@JsonDeserialize(converter = CustomObjectConverter.class)
private CustomObject customObject; 

As a result, your code will look like this. Model:

@Getter
@Setter
@NoArgConstructor
public class ParentObject{
   private String name;

   @JsonDeserialize(converter = CustomObjectConverter.class)
   private CustomObject customObject; 
}

Converter:

@Component
public class CustomObjectConverter implements 
  org.springframework.core.convert.converter.Converter<String, CustomObject>, 
  com.fasterxml.jackson.databind.util.Converter<String, CustomObject>{

   @Autowired
   private CustomObjectService customObjectService;

   @Override
   public CustomObject convert(String arg0) {
       Long id = Long.parseLong(arg0);
       return customObjectService.findById(id);
   }

   @Override
   public JavaType getInputType(TypeFactory typeFactory) {
       return typeFactory.constructType(String.class);
   }

   @Override
   public JavaType getOutputType(TypeFactory typeFactory) {
       return typeFactory.constructType(CustomObject.class);
   }
}

Upvotes: 3

Fernando Aspiazu
Fernando Aspiazu

Reputation: 993

You should implement your own JacksonCustomMapper, by extending JsonMapper and then registering it into the set of HttpMessageConverters. But, I do not recommend to pollute the default conversion, you could pass in the @RequestBody an incomplete json and Jackson will parse it to your object, it would be sufficient to not pass wrong keys in your json object... An example (among thousands) here: http://magicmonster.com/kb/prg/java/spring/webmvc/jackson_custom.html. Enjoy it :-)

Upvotes: 2

Related Questions