我有来自服务器的非常复杂的JSON响应。我需要在本地数据库中插入。
以下是我的json响应
{
"currentdate": "2018-02-27",
"data": [
{
"date": "2017-11-05",
"data": [
{
"id": 268,
"schedulId": 268,
"userId": 70,
"completedOn": "0000-00-00 00:00:00",
"currentDate": "2018-02-27",
"workouts": {
"workoutDetails": {
"workoutDetails": "1Day Gain Muscle GYM",
"workoutName": "Gain Muscle",
"day": "Day 1",
"inComplete": "0"
},
"stages": [
{
"id": 2,
"mainExerciseName": "Warmup",
"exerciseSets": 1,
"exerciseList": [
{
"exerciseId": 602,
"name": "Jumping Jacks",
"setReps": "2X25",
"sort": 0
}
]
}
]
}
}
]
}
],
"status": 200
}
如何使我的pojo类具有列清除功能。
最佳答案
您在使用改造吗?
这是您的json:
{
"currentdate": "2018-02-27",
"data": [{
"date": "2017-11-05",
"data": [{
"id": 268,
"schedulId": 268,
"userId": 70,
"completedOn": "0000-00-00 00:00:00",
"currentDate": "2018-02-27",
"workouts": {
"workoutDetails": {
"workoutDetails": "1Day Gain Muscle GYM",
"workoutName": "Gain Muscle",
"day": "Day 1",
"inComplete": "0"
},
"stages": [{
"id": 2,
"mainExerciseName": "Warmup",
"exerciseSets": 1,
"exerciseList": [{
"exerciseId": 602,
"name": "Jumping Jacks",
"setReps": "2X25",
"sort": 0
}]
}]
}
}]
}],
"status": 200
}
创建一个可以序列化该json的模型,然后在该模型的类名上方键入
@Entity (tableName = "myTableName")
。@Entity (tableName = "my_complex_model")
public class MyCompledModel {
public String currentDate;
@TypeConverter(ParentDataTypeConverter.class)
public List<ParentData> data;
}
public class ParentData {
public String date;
@TypeConverter(NestedDataTypeConverter.class)
public List<NestedData> data;
}
public class NestedData {
public int id;
public int schedulId;
public int userId;
public String completedOn;
}
等等。你明白了。
您需要为列表添加typeConverter,以便他们知道如何填充数据库中的单元格。
public class NestedDataTypeConverter {
private static Gson gson = new Gson();
private static Type type = new TypeToken<List<NestedData>>(){}.getType();
@TypeConverter
public static List<NestedData> stringToNestedData(String json) {
return gson.fromJson(json, type);
}
@TypeConverter
public static String nestedDataToString(List<NestedData> nestedData) {
return gson.toJson(nestedData, type);
}
}
然后,您需要创建一个Dao接口(interface)
@Dao
interface MyComplexModelDao {
@Query("..")
void delete(int id);
@Query("..")
void insert(MyComplexModel model);
}
最后,在数据库类中,您需要对模型进行注释。
@Database(entities = {
MyComplexModel.class, ... others }
@TypeConverters(value = {
EmployeeSlimTypeConverter.class, ... others }
public abstract class AppDatabase extends RoomDatabase {
public abstract MyComplexModelDao myComplexModelDao();
}
那样的事情,不要复制粘贴。这只是从我的脑海写的。