spring mvc返回json代码
时间: 2023-03-23 19:01:43 浏览: 87
以下是一个使用Spring MVC返回JSON的Java代码示例:
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/example")
public MyResponseObject getExample() {
MyResponseObject responseObject = new MyResponseObject();
responseObject.setName("John Doe");
responseObject.setAge(30);
return responseObject;
}
}
class MyResponseObject {
private String name;
private int age;
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
在此示例中,使用@RestController注解标注了一个控制器类,并在其中定义了一个名为getExample的请求处理方法,该方法返回一个MyResponseObject类型的对象。当请求映射到该方法时,Spring MVC将自动将该对象序列化为JSON并将其作为响应发送回客户端。