1. 程式人生 > >SpringBoot JSON檔案讀取

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":"測試"
}]
}