Json文件转Json字符串

Json文件转Json字符串

将放在resources资源文件夹下的city.json文件读取出来后转换成json字符串返回给前端

image-20211019214818314

访问接口返回json字符串

image-20211019214933923

代码如下

@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;
  }
posted @ 2021-10-19 21:57  肖恩雷  阅读(390)  评论(0编辑  收藏  举报