1.读取asset中的json文件,只需传入context和要读的json文件名即可:
StringBuilder newstringBuilder = new StringBuilder();
InputStream inputStream = null;
try {
inputStream = context.getResources().getAssets().open(fileName);
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isr);
String jsonLine;
while ((jsonLine = reader.readLine()) != null) {
newstringBuilder.append(jsonLine);
}
reader.close();
isr.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try{
String result = newstringBuilder .toString();
Gson gson = new Gson();
ProvinceCityJson provinceCityJson = gson.fromJson(result, JsonDate.class);
}catch (Exception e) {
e.printStackTrace();
Log.d("ADDB", "error====" + e.getMessage());
}
2.读取手机sd卡根目录中的json文件,传入context和json文件名即可,如文件不在根目录,可对jsonpath进行目录的更改:
StringBuffer sb = new StringBuffer();
try {
String jsonpath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName;
FileInputStream input = new FileInputStream(jsonpath);
byte[] temp = new byte[1024];
int len = 0;
//读取文件内容:
while ((len = input.read(temp)) > 0) {
sb.append(new String(temp, 0, len));
}
//关闭输入流
input.close();
} catch (Exception e) {
e.printStackTrace();
}
try{
testJsonBeans = new Gson().fromJson(sb.toString(), new TypeToken<List<TestJsonBean>>(){}.getType());
}catch (Exception e) {
e.printStackTrace();
Log.d("ADDB", "error====" + e.getMessage());
}