step1:获取数据库中的List
https://blog.csdn.net/qw160/article/details/108825246
step2:将list转化为json
添加alibaba fastjson依赖
pom.xml
这段代码添加上之后会报错
Dependency ‘com.alibaba:fastjson:1.2.76’ not found
关掉idea重新打开即可
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
将从数据库取到的数据从list转换为json
String listJson = JSON.toJSONString(list);
return listJson;
完整的控制器 lianjie.java代码
package com.json.jsondemo.controller;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
@Controller
public class lianjie {
@Autowired
JdbcTemplate jdbcTemplate;
@ResponseBody
@GetMapping("/jdbc")
//public Map<String, Object> map() {
public String map() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from customerslist");
String listJson = JSON.toJSONString(list);
return listJson;
}
}
网页访问
项目结构