fayeah / blogs

方法论、问题驱动、总结
6 stars 0 forks source link

【Springboot】Gson #26

Open fayeah opened 4 years ago

fayeah commented 4 years ago

Springboot中,有时候会出现连接外部db但是又极慢的情况,那么这个时候可能就需要自己弄一个json文件,方便本地调试:

steps:

  1. 创建一个含有所需数据的json文件(注意这个在root folder最方便);

  2. 加入Gson dependency, 在dependencies里面:

    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
    compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
  3. 实现:

    JSONParser jsonParser = new JSONParser();
    List<Model> items = null;
    try (FileReader reader = new FileReader("file.json")) {
    Object obj = jsonParser.parse(reader);
    JSONArray list = (JSONArray)obj;
    Gson gson = new Gson();
    Type type = new TypeToken<List<Model>>(){}.getType();
    items = gson.fromJson(list.toJSONString(), listType);
    } catch(FileNotFoundException e) {
    e.printStackTrace();
    } catch(IOException e) {
    e.printStackTrace();
    } catch(ParseException e) {
    e.printStackTrace();
    } 
    return items;

Note:

  1. 可能需要反序列化 // @SerializedName