为了返回复杂的json格式数据,我们可以在SpringMVC中使用Jackson库的ObjectMapper类,将java对象序列化为json字符串。下面是SpringMVC返回复杂的json格式数据的步骤。
在pom.xml文件中添加Jackson库的依赖。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.1</version>
</dependency>
创建一个Controller,其中的方法返回一个复杂的java对象,例如Map
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
public class UserController {
@RequestMapping(value="/user")
@ResponseBody
public Map<String, Object> getUserInfo() {
Map<String, Object> result = new HashMap<>();
User user = new User();
user.setName("John");
user.setAge(20);
result.put("user_info", user);
return result;
}
class User {
private String name;
private int age;
// getter and setter methods
}
}
在上述代码中,getUserInfo()方法返回一个Map
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
@Controller
public class UserController {
@RequestMapping(value="/user")
@ResponseBody
public String getUserInfo() {
User user = new User();
user.setName("John");
user.setAge(20);
Address address = new Address();
address.setProvince("Beijing");
address.setCity("Beijing");
user.setAddress(address);
return JSON.toJSONString(user);
}
class User {
private String name;
private int age;
private Address address;
// getter and setter methods
}
class Address {
private String province;
private String city;
// getter and setter methods
}
}
在上述代码中,getUserInfo()方法返回一个String类型的json格式字符串。我们使用fastjson库进行序列化,将User对象序列化为json字符串并返回。而fastjson库由于是阿里巴巴出品,所以速度和性能都不错。
启动项目,在浏览器中输入localhost:8080/user
,就会返回json格式的字符串。
同时也可以通过Postman等工具来测试。