java获取本地json格式的内容

前言

该功能模块基于springBoot,自己在开发中遇到相关功能开发,总结如写:

1.首先将所需要获取的json文件放在项目resource目录下:

java获取本地json格式的内容

2.所需要的pom依赖:

       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

3.读取JSON工具类

/**
     * 读取json文件,返回json串
     * @param fileName
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);

            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

4.测试类

public class TestJson {
 public static void main(String[] args) throws  Exception{
      // 假设我下面json文档有10个 名字:1 -10.json
       for (int j = 1; j < 10; j++) {
            String srcpath = j+".json";
            String path = ElectronicWaybillController.class.getClassLoader().getResource(srcpath).getPath();
            String s = readJsonFile(path);
            JSONObject jobj = JSON.parseObject(s);
            //构建JSONArray数组
            JSONArray movies = jobj.getJSONArray("content");
            for (int i = 0 ; i < movies.size();i++){
                JSONObject key = (JSONObject)movies.get(i);
                ElectronicWaybillDetailsDTO electronicWaybillDetailsDTO = new ElectronicWaybillDetailsDTO();
                electronicWaybillDetailsDTO.setDriverName((String)key.get("driverName"));
                electronicWaybillDetailsDTO.setAreaCode((String)key.get("organCode"));
                electronicWaybillDetailsDTO.setCanBodyNo((String)key.get("tankNum"));

                    这里字段较多,以上写以上几个作为代表

                electronicWaybillService.insert(electronicWaybillDetailsDTO);
        }
}

java获取本地json格式的内容

上一篇:C++ WIN32 日志程序


下一篇:uniapp 用view组件作为按钮 防止重复点击 我的实现方法