spring boot读取json菜单文件
一、设计思路 将菜单写在文件menu.json里,后台读取该文件,并将菜单输出到页面上。
二、技术点 1、读取JSON文件 2、序列化成实体数组 3、thymeleaf循环输出
三、具体描述1、menu.json
[{ "id": 1, "name": "home", "title": "首页", "url": "home/"},{ "id": 2, "name": "hyjj", "title": "知识经济", "url": "hyjj/"},{ "id": 3, "name": "fzjz", "title": "防灾减灾", "url": "fzjz/"},{ "id": 4, "name": "cgzh", "title": "成果转化", "url": ""}]
2、菜单项实体类
public class Menu { private int id; private String name; private String title; private String url; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
3、读取菜单1)读取json文件静态类JsonUtils
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.parser.Feature;import org.springframework.core.io.ClassPathResource;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.Type;import java.nio.charset.StandardCharsets;import java.util.List;public class JsonUtils { public static T readSingle(String path, Type type) throws IOException { ClassPathResource resource = new ClassPathResource(path); if (resource.exists()) { return JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, type, // 自动关闭流 Feature.AutoCloseSource, // 允许注释 Feature.AllowComment, // 允许单引号 Feature.AllowSingleQuotes, // 使用 Big decimal Feature.UseBigDecimal); } else { throw new IOException(); } } public static List readArray(String path, Class t) throws IOException { ClassPathResource resource = new ClassPathResource(path); if (resource.exists()) { InputStream stream = resource.getInputStream(); byte[] bytes = new byte[stream.available()]; stream.read(bytes); return JSON.parseArray(new String(bytes), t); } else { throw new IOException(); } }}
2)调用JsonUtils
public List
暂时没有评论,来抢沙发吧~