相关代码:
前提是你的springmvc其他配置已经ok的情况下
1.导入JSON相关依赖
<!--阿里的json包--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency>
2.编写一个实体类
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String address; }
3.在springmvc-servlet.xml中加入此配置
为了处理JSON格式的中文乱码
<mvc:annotation-driven> <!--JSON格式乱码处理方式--> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
4.编写Controller
@Controller public class JsonController { @GetMapping("/json") @ResponseBody public String json(){ User user = new User(1,"齐菁菁","china"); User user1 = new User(2,"詹三","china"); User user2 = new User(3,"李四","china"); List<User> list = Arrays.asList(user, user1, user2); return JSON.toJSONString(list); } }
5.启动tomcat进行访问