1.Jackson
导入Maven依赖:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.0</version> </dependency>
编写pojo类:
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; }
直接返回前端字符串,格式如下:
@ResponseBody // 不会走视图解析器,会直接返回一个字符串 @RequestMapping("/j1") public String json() { User user = new User(1, "dahezhiquan", 18); return user.toString(); }
但这不是我们想要的格式,前端希望得到一个json格式的字符串
通过Jackson,我们可以很容易的将一个字符串转化为json的格式:
实例:
@ResponseBody // 不会走视图解析器,会直接返回一个字符串 @RequestMapping("/j1") public String json1() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(1, "dahezhiquan", 18); String s = mapper.writeValueAsString(user); return s; }
2.解决Jackson的中文乱码问题
springmvc-servlet.xml添加对于中文的支持即可:
如下的配置式固定不变的:
<!--JSON乱码问题--> <mvc:annotation-driven> <mvc:message-converters> <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>
如果希望类中所有的方法不走视图解析器,直接返回一个字符串,可以使用@RestController
注解标识类
3.多种样式的json
传递多个对象使用列表:
实例:
@ResponseBody // 不会走视图解析器,会直接返回一个字符串 @RequestMapping("/j1") public String json1() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); ArrayList<User> users = new ArrayList<>(); User user1 = new User(1, "大河1", 18); User user2 = new User(2, "大河2", 18); User user3 = new User(3, "大河3", 18); users.add(user1); users.add(user2); users.add(user3); return mapper.writeValueAsString(users); }
4.Fastjson
导入Maven依赖:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.18</version> </dependency>
使用实例:
@ResponseBody @RequestMapping("/j2") public String json2() { ArrayList<User> users = new ArrayList<>(); User user1 = new User(1, "大河1", 18); User user2 = new User(2, "大河2", 18); User user3 = new User(3, "大河3", 18); users.add(user1); users.add(user2); users.add(user3); return JSON.toJSONString(users); }