zoukankan      html  css  js  c++  java
  • SpringBoot JSON文件读取

    @Component
    public class StepExecutor implements Runnable {
    @Value("classpath:menu.json")
    private Resource areaRes;
    @Override
    public void run() {
    startStreamTask();
    }


    public void startStreamTask(){
    System.out.println("==========================");
    try {
    File file = areaRes.getFile();
    String jsonData = this.jsonRead(file);
    JSONObject jsonObject = JSONObject.parseObject(jsonData);
    JSONArray array = JSONArray.parseArray(jsonObject.get("menu").toString());
    for(int i=0;i<array.size();i++){
    JSONObject jsonObject2 = array.getJSONObject(i);
    Menu m = JSONObject.toJavaObject(jsonObject2,Menu.class);
    System.out.println("name:"+m.getName());
    System.out.println("id:"+m.getId());
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    private String jsonRead(File file){
    Scanner scanner = null;
    StringBuilder buffer = new StringBuilder();
    try {
    scanner = new Scanner(file, "utf-8");
    while (scanner.hasNextLine()) {
    buffer.append(scanner.nextLine());
    }
    } catch (Exception e) {

    } finally {
    if (scanner != null) {
    scanner.close();
    }
    }
    return buffer.toString();
    }
    }

    menu.json文件在 resources 下:

    格式是这样的:

    {
    "menu":
    [{
    "id":1,
    "name":"测试"
    }]
    }
  • 相关阅读:
    CSS练习
    大作业“抽屉页面”html+css
    html练习代码
    协程-基于TCP的高并发通信
    协程-爬虫示例
    互斥锁,递归锁,信号量
    三层架构(我的理解及详细分析)
    递归算法经典实例小结(C#实现)
    使用XmlWriter写Xml
    使用XmlReader读Xml
  • 原文地址:https://www.cnblogs.com/duanqiao123/p/9911720.html
Copyright © 2011-2022 走看看