代码之家  ›  专栏  ›  技术社区  ›  Philip

Spring boot server如何将json转换为请求对象

  •  0
  • Philip  · 技术社区  · 6 年前

    抱歉,我是Spring boot的新手,但我正在尝试向服务器添加新的API,其他人写道:

      @RequestMapping(value = RequestMappingConstants.CREATE_POST, method = RequestMethod.POST)
      public @ResponseBody Map<String, Object> createPost(@RequestBody Map<String, String> inputMap, HttpServletRequest request) {
        LOG.info("Inside createPost");
        return DataUtil.ConvertToResponseMap(socialService.createPost(CreatePostRequest.fromMap(inputMap)));
      }
    

    在这个控制器方法中,我接受一个映射,但它给出了以下错误:

    组织。springframework。http。转换器。HttpMessageTreadableException:JSON解析错误:无法反序列化的实例 java.lang.String 启动外\u对象令牌;嵌套的异常是com。fasterxml。杰克逊。数据绑定。exc.mismatchdinPutException:无法反序列化的实例 JAVA串 启动外\u对象标记

    这是因为我在请求对象中有一个嵌套的BaseUser对象。

    理想情况下,我希望该方法如下所示,采用请求对象而不是映射:

      @RequestMapping(value = RequestMappingConstants.CREATE_POST, method = RequestMethod.POST)
      public @ResponseBody Map<String, Object> createPost(@RequestBody CreatePostRequest request) {
        LOG.info("Inside createPost");
        return DataUtil.ConvertToResponseMap(socialService.createPost(request));
    }
    

    但在填充嵌套对象BaseUser时也存在问题。 所以我想知道,服务器的哪个部分将原始json转换为映射,或者将原始json转换为请求对象? 我没有找到任何代码可以这样做。还是在注释中?我需要为它编写一些东西来解析json中的嵌套对象吗?

    这是我的请求对象:

    public class CreatePostRequest extends BaseRequest
    {
        public BaseUser user;
        public String imageUrl;
        public String text;
    }
    

    以及BaseUser对象:

    public class BaseUser {
        public int userId;
        public String firstName;
        public String lastName;
        public int hairType;
        public String location;
        public String profileImageUrl;
    
        public BaseUser(){}
    
        public BaseUser(int userId, String firstName, String lastName, int hairType, String location, String profileImageUrl)
        {
            this.userId = userId;
            this.firstName = firstName;
            this.lastName = lastName;
            this.hairType = hairType;
            this.location = location;
            this.profileImageUrl = profileImageUrl;
        }
    }
    
    0 回复  |  直到 6 年前