版本android studio 3.4.1
1.创建一个json文件:首先在src/main/下建一个assets文件夹,然后再assets下建一个xxxx.json文件,把数据按照json格式写到文件中即可
我的json文件名为province.jason,数据格式如下:
{
"province":
[
{"id":1, "name": "北京"},
{"id":2, "name": "上海"},
{"id":3, "name": "天津"},
{"id":4, "name": "重庆"},
{"id":5, "name": "香港"},
{"id":6, "name": "澳门"},
{"id":7, "name": "台湾"},
{"id":8, "name": "黑龙江"},
{"id":9, "name": "吉林"},
{"id":10, "name": "辽宁"},
{"id":11, "name": "内蒙古"},
{"id":12, "name": "河北"}
]
}
2.读取json文件:
try {
InputStream is = MainActivity.this.getClass().getClassLoader().
getResourceAsStream("assets/"+"province.json");
InputStreamReader streamReader = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(streamReader);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null){
Log.d("coolWeather", "line=" + line);
stringBuilder.append(line);
}
reader.close();
reader.close();
is.close();
}catch (IOException e){
e.printStackTrace();
}
如果你不是在MainActivity下编辑的这段代码,把其中的MainActivity换成你当前的活动名就ok了