![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8209245e2f888e88110dbcb0f9ad1e94.png)
springBoot内使用JSON,返回对象
–pom.xml 中添加 Web 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
–
–启动类:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
–
–新建 model 包,在包下新建⼀个User类:
public class User {
private String name;
private int age;
private String pass;
//setter、getter省略
}
–
–在项⽬中新建 Web 包,并在 Web 包下新建⼀个类 WebController,在类中创建⼀个⽅法返回 User:
package com.example.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebController {
@RequestMapping(value="/getUser", method= RequestMethod.POST)
public User getUser() {
User user=new User();
user.setName("小明");
user.setAge(12);
user.setPass("123456");
return user;
}
}
–
–在 test 包下新建 WebControllerTest 测试类,对 getUser()测试。
package com.example.demo;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
public class WebControllerTest {
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(new WebController()).build();
}
@Test
public void getUser() throws Exception {
String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/getUser"))
.andReturn().getResponse().getContentAsString();
System.out.println("result : "+responseString);
}
}
执行Junit Test:
说明 Spring Boot ⾃动将 User 对象转成了 JSON 进⾏返回。