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":"测试"
}]
}
posted @ 2018-11-05 21:35  Birdgeduan  阅读(19699)  评论(1编辑  收藏  举报