创建要在Spring引导测试中发布的JSON对象

创建要在Spring引导测试中发布的JSON对象,json,spring,spring-boot,Json,Spring,Spring Boot,我想写一个基本的测试,用JSON负载在/users URL上执行POST请求,以创建一个用户。我找不到如何将一个新对象转换为JSON,到目前为止,我有这么多,这显然是错误的,但解释了目的: @Test public void createUser() throws Exception { String userJson = new User("My new User", "myemail@gmail.com").toJson(); this.mockMvc.perform(pos

我想写一个基本的测试,用JSON负载在/users URL上执行POST请求,以创建一个用户。我找不到如何将一个新对象转换为JSON,到目前为止,我有这么多,这显然是错误的,但解释了目的:

@Test public void createUser() throws Exception {
    String userJson = new User("My new User", "myemail@gmail.com").toJson();
    this.mockMvc.perform(post("/users/").contentType(userJson)).andExpect(status().isCreated());

您可以使用jackson对象映射器,然后使用user writeValueAsString方法

所以


我希望这能帮到你

正是我想要的:O)你能用你的见解看看我的帖子吗@我很困惑你的问题你解决了吗?我在对你的问题的评论中问了一些问题,这对我来说并不清楚
@Autowired
ObjectMapper objectMapper;

// or ObjectMapper objectMapper = new ObjectMapper(); this with Spring Boot is useless


    @Test public void createUser() throws Exception {
        User user = new User("My new User", "myemail@gmail.com");
        this.mockMvc.perform(post("/users/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(user)))
                .andExpect(status().isCreated());
    }