读取JSON文件,封装成对象
Gson、流
gson.fromJson
- 引入依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
2、
public static Map<String,Object> readJsonFile(String fileName){
Gson gson = new Gson();
String json = "";
File file = new File(fileName);
try {
Reader reader = new InputStreamReader(new FileInputStream(file),"utf-8");
int ch = 0;
StringBuffer buffer = new StringBuffer();
while ((ch = reader.read())!= -1){
buffer.append((char) ch);
}
reader.close();
json = buffer.toString();
return gson.fromJson(json,Map.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
测试
public static void main(String[] args) {
System.out.println(readJsonFile("D:\workspace\ZhuStudy\Demo01\src\main\resources\abc.json"));
}
}