JsonUtil 工具類:獲取Json轉化成集合

  根據 Json 路徑 把 Json 轉化成 對應對象的 List 集合 的 工具類

/**
 * @Author: wangmx
 * @Description: 讀取 json 文件 轉成 對應 集合 類型
 */
public class JsonUtil {

 	/**
     * @param name json路徑
     * @return
     */
    public String json(String name){
        StringBuffer stringBuffer = new StringBuffer();
        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream(name);
            BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                stringBuffer.append(line);
            }
            String s = stringBuffer.toString();

            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 獲取 json 加強版
     * @param jsons json 路徑
     * @param clazz 對象
     * @param <T>
     * @return
     */
    public <T>List<T> jsonLists(String jsons, Class<T> clazz){
        try {
            //獲取json
            String json = this.json(jsons);

            List<T> rateList = JSONObject.parseArray(json,clazz);
            return rateList;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }



}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章