【问题标题】:Encoding the request body编码请求正文
【发布时间】:2018-05-27 10:20:09
【问题描述】:

我正在使用一个简单的表单,用户可以在其中输入一些 JSON。 我将该输入添加到请求的正文中。 当我从正文中检索值时,它没有被格式化/编码为 JSON。 相反,我得到类似 json=%7B%22vrt%22%3A%7B ... 如何/在哪里指定正文中的值必须是 JSON,以便我的控制器可以使用 GSON 解析它?

提前致谢。 问候

控制器

@PostMapping(value = "/api/sendMessage")
public ModelAndView sendIoTMessage(@RequestBody String json) {
    VehicleMessage vehicleMessage = new Gson().fromJson(json, VehicleMessage.class);
    MessageProcessor.postVehicleMessage(vehicleMessage);
    ModelAndView mav = new ModelAndView();
    mav.setViewName("iot");
    return mav;
}

表格

<form id="sendMessage" th:action="@{/api/sendMessage}" method="post">
    <div class="form-group">
        <input class="form-control" th:value="*{json}" id="json" name="json">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

【问题讨论】:

    标签: json spring spring-mvc spring-boot


    【解决方案1】:

    默认情况下,Spring APPLICATION JSON 使用 Jackson 转换器,如果要使用 GSON 转换器,则需要添加 GSONConvertor。

    我个人更喜欢选项 1

    添加GSONConvertor的不同方式:

    1. 使用 JavaConfig

      @Configuration @EnableWebMvc
      public class Application extends WebMvcConfigurerAdapter {
      
      @Override
      public void configureMessageConverters(List<HttpMessageConverter < ? >> converters) {
          GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
          converters.add(gsonHttpMessageConverter);
      }
      

      }

    2. 使用自定义转换器

      @配置 公共类 CustomConfiguration {

      @Bean
      public HttpMessageConverters customConverters() {
      
          Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
      
          GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
          messageConverters.add(gsonHttpMessageConverter);
      
          return new HttpMessageConverters(true, messageConverters);
      }
      

      }

    3. 使用自动配置 ..follow this link

    【讨论】:

    • 使用选项 1 我得到以下信息:由处理程序执行引起的已解决异常:org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型'application/x-www-form-urlencoded'
    • 默认情况下GsonHttpMessageConverter不支持“application/x-www-form-urlencoded”,它支持“application/json”,如果要读取请求“application/x-www-form-urlencoded”,那么您需要通过扩展 GsonHttpMessageConverter 创建自定义 GSON 转换器,并使用 spring 注册该自定义转换器 ..如选项 1 中所述
    【解决方案2】:

    为什么不让 Spring 为您(反)序列化 JSON?此功能应开箱即用,无需任何自定义配置。

    @PostMapping(value = "/api/sendMessage", consumes="application/json")
    public ModelAndView sendIoTMessage(@RequestBody VehicleMessage vehicleMessage) {
        MessageProcessor.postVehicleMessage(vehicleMessage);
        ModelAndView mav = new ModelAndView();
        mav.setViewName("iot");
        return mav;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多