Json文件转Json字符串
将放在resources资源文件夹下的city.json文件读取出来后转换成json字符串返回给前端
访问接口返回json字符串
代码如下
@GetMapping("/city")
public String getCityInfo() {
String jsonStr = "";
InputStreamReader reader = null;
Resource resource = new ClassPathResource("city.json");
try {
InputStream is = resource.getInputStream();
reader = new InputStreamReader(is, "UTF-8");
StringBuffer sb = new StringBuffer();
int ch = 0;
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
jsonStr = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭文件流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return jsonStr;
}