1 导入jackson jar包
jackson-annotations-2.5.4.jar
jackson-core-2.5.4.jar
jackson-databind-2.5.4.jar
2 配置json转换器
在对应的mvc.xml中配置
<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
3 后台
@Controller
public class JsonTest {
@RequestMapping("/jsontest")
@ResponseBody//表示返回的是个json对象会经过配置文件转换
public User sd() throws Exception {
User user = new User();
user.setUsername("李贤");
return user;
}
}
4 前台
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
alert("123")
$("#btn").click(function(){
$.ajax({
type:"POST",
url:"jsontest",
success:function(data){
alert("成功");//不是list不用写为data[0]
alert(data.username);
},
error:function(jqXHR,textStatus,errorThrown){
alert("error");
}
});
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="getvalue">
</body>
</html>
可传值list
public List<User> showUser(){
List list = new ArrayList();
User u1=new User("1","zhangsan");
User u2=new User("1","zhangsan");
list.add(u1);
list.add(u2);
return list;
}
取值是data[index]. 取值