如果发布的参数不匹配,SpringController @requestBody注释400错误请求

时间:2016-12-21 19:09:56

标签: java json spring

使用jackson进行序列化/反序列化

<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

Spring Controller Class

@RequestMapping(value = { "/updateUsers" }, method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseJson updateUsers(@RequestBody UserProfileBean userProfileBean,  HttpSession reqSession)
    {
//do something
}

Bean Class

public class UserProfileBean {
    List<SearchContactDetails> users;

    public List<SearchContactDetails> getUsers() {
        return users;
    }

    public void setUsers(List<SearchContactDetails> users) {
        this.users = users;
    }
}

public class SearchContactDetails {

    private String userName;
    private String userId;
//getters and setters
    }

现在,如果我从我的UI浏览器调用此URL,但我收到了错误的请求-400

检查我发送给控制器的JSON错过了userName密钥

所以如果我在请求正文中传递两个参数

,这都有效
{
  "users": [
    {
      "userName": "test1",
      "userId": "1"
    },
    {
      "userName": "test2",
      "userId": "2"
    }
  ]
}

如果我错过了userName,400个错误的请求,对我来说,用户名是一个可选字段,但有些工作方式不行,有没有办法可以声明这些字段是可选的

{
  "users": [
    {
      "userId": "1"
    },
    {
      "userId": "2"
    }
  ]
}

0 个答案:

没有答案