- 使用到的类 Gson
- 在Android Studio中搜索Gson library dependcies 只能使用小写,gson;否则会搜不到;
- JsonReader是使用google的JsonReader,在导入Gson library的时候,已经导入了;
- json文件上的字段,应与你建立的数据库表字段保持一致,否则会出错
-
public class Student { @PrimaryKey @NonNull @ColumnInfo(name = "stu_id") private long stu_id; @NonNull @ColumnInfo(name = "name") private String name; //身份证 @ColumnInfo(name = "ID") private String ID; //性别 0-男 1-女 @ColumnInfo(name = "sex") private int sex; }
- json文件
[ { "stu_id":1000, "ID": "410923198910162546", "name": "张三", "sex":1 }, { "stu_id":1001, "ID": "410923198910162545", "name": "李四", "sex":2 } ]
-
- 使用Type 、TypeToken
- 整体代码
InputStream inputStream = getApplicationContext().getAssets().open("students_file.json"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); JsonReader jsonReader = new JsonReader(inputStreamReader); Gson gson = new Gson(); Type type = new TypeToken<List<Student>>(){}.getType(); List<Student> mstus=gson.fromJson(jsonReader, type);
原文地址:https://www.cnblogs.com/endian11/p/11929207.html
时间: 2024-10-19 14:27:25