81,092
社区成员
发帖
与我相关
我的任务
分享
package com.example.fuxi.controller;
import com.example.fuxi.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
//produce:指定响应体的返回类型和编码-----防止返回到页面乱码
@RequestMapping(value = "/json",produces = "application/json;charset=utf-8") //String 的转换格式 produces = "text/html;charset=utf-8"
@ResponseBody
public String json1(){
User user = new User("十五万","11","男");
ObjectMapper mapper = new ObjectMapper(); //需要一个jackson的对象映射器,也就是一个类,可以将对象转换为字符串
String userJson = null;
try {
userJson = mapper.writeValueAsString(user); //将一个java对象,转换成字符串
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(userJson);
return userJson;
}
}
@RequestMapping(value = "/json2",produces = "application/json;charset=utf-8") //String 的转换格式 produces = "text/html;charset=utf-8"
@ResponseBody
public String json2 () throws JsonProcessingException {
User user = new User("李太白","26","男");
return new ObjectMapper().writeValueAsString(user);
}
@RequestMapping(value = "/json3",produces = "application/json;charset=utf-8") //String 的转换格式 produces = "text/html;charset=utf-8"
@ResponseBody
public String json3 () throws JsonProcessingException {
List<User> list = new ArrayList<User>();
list.add(new User("李太白1","26","男"));
list.add(new User("李太白2","25","男"));
list.add(new User("李太白3","24","男"))
list.add(new User("李太白4","23","男"));
return new ObjectMapper().writeValueAsString(list);
}
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>