版权声明:尊重原创 https://blog.csdn.net/qq_41256709/article/details/88416414
方式一
①:在pom.xml中加入依赖:
<!-- 映射JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>
②:controller:
@RequestMapping("testJson")
@ResponseBody
public User testJson() {
User user = new User();
user.setId(1);
user.setIdentity(1);
user.setName("测试员");
user.setPassword("123456");
return user;
}
③:html代码块:
$.ajax({
url: "/testJson",
type: "post",
data: {},
dataType: "json",
success: function (res) {
console.log(res);
$.each(res,function (index,r) {
//index表示下标,r表示每一次迭代所产生的对象
//二维遍历类似,再套一层
alert(index+" ===== "+r);
})
}
})
方式二
①:在pom.xml中加入以下依赖:
<!--阿里巴巴的JSON转换器-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
②:controller:
@RequestMapping("testJson")
@ResponseBody
public String testJson() {
User user = new User();
user.setId(1);
user.setIdentity(1);
user.setName("测试员");
user.setPassword("123456");
//这里是以String类型返回,JSON还有其他几种返回数据的方法
return JSON.toJSONString(user);
}
③:html代码块:
$.ajax({
url: "/testJson",
type: "post",
data: {},
dataType: "json",
success: function (res) {
console.log(res);
$.each(res,function (index,r) {
alert(index+" ===== "+r);
})
}
})
遇到的问题:
在pom.xml文件中引入依赖之后,启动项目报:
java.lang.NoClassDefFoundError: ******
诸如此类的错误,往往是因为项目启动后没有在target中加载出所需的jar包。
解决办法:将所需jar包放入lib下即可。
新手上路,如有错误欢迎指出!