将嵌套的Json发布到弹簧控制器

时间:2013-08-30 07:14:10

标签: java json spring spring-mvc

我正在尝试在spring控制器中检索嵌套的json并获得400(错误请求)错误。

JSON

{"AuthenticationInfo":
  {"loginId":"243324","password":"xyz"}
}

控制器

  @RequestMapping(value = "/login", method = RequestMethod.POST,headers={"Accept=*/*","content-type=application/json"})
    @ResponseBody
    public MySubscriber getSubscriber(@RequestBody MyAuthentication myAuthentication) {
        LOGGER.log(Level.INFO, "getSubscriber");

        System.out.println("getSubscriber method : "+myAuthentication);


        MySubscriber mySubscriber = helloWebService.getSubscriber(myAuthentication);
        LOGGER.log(Level.INFO, "mySubscriber : " + mySubscriber);
        System.out.println( "mySubscriber : " + mySubscriber);
        return mySubscriber;
    }

MyAuthentication

public class MyAuthentication extends AuthenticationInfo {
    private AuthenticationInfo AuthenticationInfo;

    public AuthenticationInfo getAuthenticationInfo() {
        return AuthenticationInfo;
    }

    public void setAuthenticationInfo(AuthenticationInfo authenticationInfo) {
        AuthenticationInfo = authenticationInfo;
    }

    @Override
    public String toString()
    {
        return "AuthenticationInfo : "+AuthenticationInfo;
    }
}

AuthenticationInfo

    public class AuthenticationInfo {
        private String loginId;
        private String password;
        public String getLoginId() {
            return loginId;
        }
        public void setLoginId(String loginId) {
            this.loginId = loginId;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }

        @Override
        public String toString()
        {
            return "{ loginId : "+loginId+" || password"+password+"}";
        }
    }

当我触发简单的Json并相应地检索它时,错误就会消失。这里唯一的问题是Json的嵌套结构

2 个答案:

答案 0 :(得分:3)

尝试像这样修改MyAuthentication

    public static class MyAuthentication extends AuthenticationInfo {
    @JsonProperty("AuthenticationInfo")
    private AuthenticationInfo AuthenticationInfo;

    public IndexController.AuthenticationInfo getAuthenticationInfo() {
        return AuthenticationInfo;
    }

    public void setAuthenticationInfo(IndexController.AuthenticationInfo authenticationInfo) {
        AuthenticationInfo = authenticationInfo;
    }

    @Override
    public String toString() {
        return "AuthenticationInfo : " + AuthenticationInfo;
    }
}

Jackson的默认jsoin属性以小写字母开头。

答案 1 :(得分:1)

现在无论我说什么都可能听起来很愚蠢。我不确定这只是杰克逊或任何其他JSON库的行为。

它会工作,我已经测试过,你只需要改变在MyAuthentication类中声明的私有属性的大小写。使用类似下面的内容:

private AuthenticationInfo authenticationInfo;

现在您还必须更改请求以匹配大小写,因此请使用以下内容:

{"authenticationInfo":{"loginId":"abcsdsd","password":"adsfsdfsdbcsdsd"}}

这完全没问题。