解析本地json檔案,模擬網路請求
阿新 • • 發佈:2019-01-02
/** * Demo class * * @author yyd * @date 2017/11/15 */ public class ParseLocalJsonUtil { /** * 從asset路徑下讀取對應檔案轉String輸出 * <p> * <p> * url = "file:///android_assets/center/helper.json"; * * @param mContext * @return */ public static String getJson(Context mContext, StringfileName) { // TODO Auto-generated method stub StringBuilder sb = new StringBuilder(); AssetManager am = mContext.getAssets(); try { BufferedReader br = new BufferedReader(new InputStreamReader( am.open(fileName))); String next = ""; while (null != (next = br.readLine())) { sb.append(next); }} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); sb.delete(0, sb.length()); } return sb.toString().trim(); } public static <T> T getJsonObject(Context mContext, String fileName, Class<T> clazz) { AssetManager am = mContext.getAssets(); try{ return JSON.parseObject(am.open(fileName), clazz); } catch (IOException e) { e.printStackTrace(); } return null; } public static <T> List<T> getJsonList(Context mContext, String fileName, Class<T> clazz) { StringBuilder sb = new StringBuilder(); AssetManager am = mContext.getAssets(); try { BufferedReader br = new BufferedReader(new InputStreamReader( am.open(fileName))); String next = ""; while (null != (next = br.readLine())) { sb.append(next); } return JSON.parseArray(sb.toString(), clazz); } catch (IOException e) { e.printStackTrace(); } return null; } }
使用方法:
2、把做好的json資料入到assets/目錄下。
3、呼叫 ParseLocalJsonUtil.getJsonList(mContext, "data/data.json", CompetitionRankingBean.class);
ParseLocalJsonUtil.getJsonObject(mContext, "data/data.json", CompetitionRankingBean.class);
實現自己想要的結果