【问题标题】:JSON encoding using produces={"application/json; charset=UTF-8"} and ObjectMapperJSON 编码使用produces={"application/json; charset=UTF-8"} 和ObjectMapper
【发布时间】:2017-12-10 02:22:46
【问题描述】:

我正在尝试使用 Spring MVC 和 Spring Boot 开发微服务。在我的服务中,我将结果返回为 JSON 编码格式。目前我添加了如下操作:

@RequestMapping("/checkUsers")
    public String checkLogin() throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        List<Users> useObj = (List<Users>) userRepo.findAll();
        return(mapper.writeValueAsString(useObj));
    }

现在我通过以下方法找到了其他选项

produces={"application/json; charset=UTF-8"} 

这里我不确定在 Spring 中正确使用哪种方法将数据编码为 JSON 格式。我该如何继续?

【问题讨论】:

标签: json spring-boot


【解决方案1】:

你为什么不直接使用 响应实体

然后返回 new ResponseEntity&lt;String&gt;(“your message”, HttpStatus.OK);

【讨论】:

    【解决方案2】:
    @RequestMapping(method = GET, value = "my/random/uri", produces = "application/json;charset=UTF-8")
    

    @RequestMapping 注释中的 produces 属性是映射请求的可生产媒体类型。格式是单个媒体类型或一系列媒体类型,只有在提到的与这些媒体类型之一匹配时才会映射请求。在这里,我的 @RequestMapping 注释已经用于我的编码目的。

    现在来自 Spring Boot 文档:

    Spring Boot 是一个全新的框架,旨在简化新 Spring 的引导和开发 应用。该框架采用自以为是的方法 配置,使开发人员无需定义样板文件 配置。

    请不要扼杀 Spring Boot 的目的。 :)

    另外,我建议你使用 org.springframework.http.MediaType 类。它具有您需要的所有编码类型。编码愉快。

    如果您在采用建议的方法时遇到任何困难,请告诉我。

    【讨论】:

      【解决方案3】:

      如果你在你的控制器上使用@RestController,所有的请求映射都会默认产生application/json。

      另外,也不需要自己去映射对象,只需要返回没有映射的对象,让 Spring/Jackson 来做。

      @RestController
      public class UsersController {
          // @RequestMapping("/checkUsers")
          // There is an even simpler and more concise
          @GetMapping("/checkUsers")
          public List<User> checkLogin() throws JsonProcessingException { 
              return userRepo.findAll(); 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-31
        • 1970-01-01
        • 2020-03-20
        • 2013-05-09
        • 1970-01-01
        • 2020-08-09
        • 2018-07-24
        • 2015-11-01
        相关资源
        最近更新 更多