获取assets资源
assets文件夹目录与java目录时同级
/** * 获取Assets 文件内容 * @param fileName 文件名 * @param context context * @return String */ public static String getJson(String fileName, Context context) { //将json数据变成字符串 StringBuilder stringBuilder = new StringBuilder(); try { //获取assets资源管理器 AssetManager assetManager = context.getAssets(); //通过管理器打开文件并读取 BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName))); String line; while ((line = bf.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); }
gosn解析json
Gson gson=new Gson(); Bean data=gson.fromJson(string,Bean.class);//Bean时定义的实体类 // 从assets中获取json内容并解析 //json内容为 /* [{"center":[116.41338310930209,37.60701416950952],"id":"0-0"}] //注:类型为Bean */ try { JSONArray gridDataList = new JSONArray(Utils.getJson("map_grid_data.json", HomeActivity.this));//获取JSONArray Type listType = new TypeToken<List<Bean>>() { }.getType();//获取类型 List<Bean> list = new Gson().fromJson(gridDataList.toString(), listType); Log.d("HomeActivity", list.toString()); } catch (JSONException e) { e.printStackTrace(); }