【问题标题】:How send bson via Spring @response body如何通过 Spring @response body 发送 bson
【发布时间】:2013-08-30 04:45:44
【问题描述】:

我正在使用@Responsebody String 来发送 JSON。 我的部分代码如下。(对不起,我把它全部打开了)

@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;

}

实际上它发送的是 Json。但我的客户要求 Bson 类型。如何在不编辑全局格式的情况下将 Json 更改为 Bson(我的 json 实际上只是字符串,我听说 spring 无法响应 bson。是吗?)。

【问题讨论】:

    标签: json spring annotations response bson


    【解决方案1】:

    你需要注册一个HttpMessageConverter 可以转换成BSON。

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

    不幸的是 Spring 没有 Bson Http 消息转换器,所以你必须自己实现。 (或者在 google 的时候运气比我好)。

    【讨论】:

      【解决方案2】:

      这是一个老问题,但它几乎是我能在网上找到的关于这个主题的唯一内容。

      所以这里是如何做到这一点。 假设您在 Spring 中使用 Jackson 作为 JSON 库。

      1. 将依赖项添加到Michel Krämer's bson4jackson library
      2. 像这样创建一个类:
      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. 将其作为@Bean 添加到您的配置中,或使用@Component 对其进行注释,并确保它位于您的@ComponentScan 路径中。

      就是这样。现在,如果您使用 @RequestMapping(produces = "application/bson")(以某种形式)声明您的 MVC 端点,则输出将是您的 ResponseEntity 正文的 BSON 编码。

      这适用于通常序列化为 JSON 的带有 Jackson 注释的对象;并且您通过 Spring、模块或注释对 Jackson ObjectMapper 所做的所有配置都将适用。

      它也适用于输入和输出。

      它也适用于Feign clients。 我认为它也适用于 Spring 的RestTemplate

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-16
        • 2014-03-20
        • 2011-07-30
        • 2022-11-20
        • 1970-01-01
        • 2018-06-06
        • 1970-01-01
        相关资源
        最近更新 更多