import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.codehaus.jettison.json.JSONObject; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; public class JsonTool { /** * 文件相对路径(文件内容在最下方) */ private static String FILE_DIR = "项目名/src/main/resources/file.json"; /** * 获取MOCK数据 * * @since 2024/6/25 */ public static List getMockData(String dateType) { try { // 读取JSON文件内容 String content = new String(Files.readAllBytes(Paths.get(FILE_DIR))); // 通过key获取value String jsonStr = new JSONObject(content).getJSONArray(dateType).toString(); ObjectMapper objectMapper = new ObjectMapper(); List<Map> list = objectMapper.readValue(jsonStr, new TypeReference<List<Map>>() { }); return list; } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { JsonTool.getMockData("data1"); } } /** * file.json文件内容 * * { * "data1": [ * { * "taskSheetNo": "TASK_SHEET_NO_001", * "status": 1, * "isAllComplete": false, * "createTime": "2024-06-01" * }, * { * "taskSheetNo": "TASK_SHEET_NO_002", * "status": 1, * "isAllComplete": false, * "createTime": "2024-06-01" * } * ], * "data2": [ * { * "taskSheetNo": "TASK_SHEET_NO_001", * "status": 1, * "isAllComplete": false, * "createTime": "2024-06-01" * }, * { * "taskSheetNo": "TASK_SHEET_NO_002", * "status": 1, * "isAllComplete": false, * "createTime": "2024-06-01" * } * ] * } */
标签:java,读取,2024,JSON,SHEET,file,import,String From: https://www.cnblogs.com/jadening/p/18350791