This is an old question, but it is nigh the only thing I can find on the web on this topic.
So here's how to do it. Assuming you're using Jackson as your JSON library in Spring.
- Add a dependency to Michel Krämer's bson4jackson library
- Create a class like so:
import com.fasterxml.jackson.databind.ObjectMapper;
import de.undercouch.bson4jackson.BsonFactory;
import de.undercouch.bson4jackson.BsonGenerator;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import javax.annotation.Nonnull;
public class MappingJackson2BsonHttpMessageConverter
extends AbstractJackson2HttpMessageConverter
{
public MappingJackson2BsonHttpMessageConverter(@Nonnull Jackson2ObjectMapperBuilder builder) {
super(bsonObjectMapper(builder), MediaType.parseMediaType("application/bson"));
}
@Nonnull
private static ObjectMapper bsonObjectMapper(@Nonnull Jackson2ObjectMapperBuilder om){
BsonFactory f = new BsonFactory();
f.configure(BsonGenerator.Feature.ENABLE_STREAMING, true);
return om.factory(f).build();
}
}
- Add it as a
@Bean
to your configuration, or annotate it with @Component
and make sure it's in your @ComponentScan
's path.
That's it. Now, if you declare your MVC endpoint with @RequestMapping(produces = "application/bson")
(in some form or another), the output will be the BSON encoding of your ResponseEntity's body.
This works with Jackson-annotated Objects which you'd normally serialize to JSON; and all the configuration you did to the Jackson ObjectMapper
through Spring, modules or annotations will apply.
It also works for input as well as for output.
It also works with Feign clients.
I assume it also works with Spring's RestTemplate
.