Question

I am using @Responsebody String to send JSON. part of my code is below.(I am sorry for open it all)

@RequestMapping(value = "/getSomeList", method = RequestMethod.GET ,
            headers="Accept=application/json", produces = "text/plain;charset=UTF-8")
    public @ResponseBody String getThumbList(
            @RequestParam("con_id") String con_id) throws Exception{
return json;

}

And actually it sends Json. But my client requests Bson type. How can I change Json to Bson without editing global format(my json is actually just string and I heard that spring can not response bson. Is that right?).

Was it helpful?

Solution

You need to register a HttpMessageConverter that can convert to BSON.

<mvc:annotation-driven>
     <mvc:message-converters>
          <bean class="MyBsonHttpMessageConverter"/>
     </mvc:message-converters>
</mvc:annotation-driven>

Unfortunaly Spring has no Bson Http Message Converter, so you have to implement your own. (Or have more luck then me while google for one).

OTHER TIPS

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.

  1. Add a dependency to Michel Krämer's bson4jackson library
  2. 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();
    }
}

  1. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top