Java 无法在Gson自定义反序列化程序内初始化Android.Util.Pair
我正在为当前应用程序中的数据模型创建一个Java 无法在Gson自定义反序列化程序内初始化Android.Util.Pair,java,android,json,junit,deserialization,Java,Android,Json,Junit,Deserialization,我正在为当前应用程序中的数据模型创建一个自定义反序列化程序,在尝试初始化自定义反序列化程序中的对时遇到一些问题。我从Json中恢复项目A和B,它们可以从JsonObject正确初始化,但是当我想用它们创建新对(A,B)时,我得到一个异常: 方法引发了“java.lang.RuntimeException”异常。无法计算android.util.Pair.toString()的值 我一直在寻找更多有相同问题的人,但是我找不到任何关于这个问题的提示,我不知道为什么我不能在反序列化器中初始化该项。我在
自定义反序列化程序
,在尝试初始化自定义反序列化程序
中的对
时遇到一些问题。我从Json中恢复项目A和B,它们可以从JsonObject
正确初始化,但是当我想用它们创建新对(A,B)
时,我得到一个异常:
方法引发了“java.lang.RuntimeException”异常。无法计算android.util.Pair.toString()的值
我一直在寻找更多有相同问题的人,但是我找不到任何关于这个问题的提示,我不知道为什么我不能在反序列化器中初始化该项。我在一个junit
测试中执行我的所有代码,所以可能是因为这个原因,但我不知道为什么。这是我的反序列化程序的代码
:
public class CustomSetDeserializer implements JsonDeserializer<ExerciseSet> {
private List<Exercise> exerciseList;
public CustomSetDeserializer(List<Exercise> exerciseList) {
this.exerciseList = exerciseList;
}
@Override
public ExerciseSet deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<Pair<Exercise, Integer>> setExercises = new ArrayList<>();
JsonArray exercisesJsonArray = json.getAsJsonObject().get("exercises").getAsJsonArray();
for (JsonElement jsonElement : exercisesJsonArray) {
String name = jsonElement.getAsJsonObject().get("name").getAsString();
int reps = jsonElement.getAsJsonObject().get("reps").getAsInt();
Exercise exercise = getExercise(name);
setExercises.add(new Pair<>(exercise, reps));
}
int exercisesPerRound = json.getAsJsonObject().get("exercisesPerRound").getAsInt();
int restBetweenRounds = json.getAsJsonObject().get("restBetweenRounds").getAsInt();
ExerciseSet set;
switch (exercisesPerRound) {
case 3:
//TODO TRISET
set = new SimpleSet(setExercises, restBetweenRounds);
break;
case 2:
//TODO SUPERSET
set = new SimpleSet(setExercises, restBetweenRounds);
break;
default:
set = new SimpleSet(setExercises, restBetweenRounds);
break;
}
return set;
}
private Exercise getExercise(String name){
for (Exercise exercise : exerciseList) {
if (!exercise.name().equals(name)) continue;
return exercise;
}
throw new IllegalArgumentException("Wrong exercise name");
}
}
如果我调试代码,一切正常,但是从来没有创建过对,因此我总是在Junit测试中检索一个满是null对的列表,您不能引用android代码(android.util.Pair
),由于此测试是在本地jvm中执行的,因此没有要初始化的类
考虑使用lib来模拟android类,或者在代码中抽象它们,不要使用具体化(android框架类),而是使用这种抽象并用Mockito来模拟它们
@Test
public void read_set_json() {
CustomSetDeserializer customSetDeserializer = new CustomSetDeserializer(exercises);
Gson gson = new GsonBuilder().registerTypeAdapter(ExerciseSet.class, customSetDeserializer).enableComplexMapKeySerialization().create();
ExerciseSet set = gson.fromJson(setExample, ExerciseSet.class);
assertThat(set.exercises().get(0).first.equals(exercise), is(true));
assertThat(set.exercises().get(0).second.equals(12), is(true));
assertThat(set.rounds(), is(4));
assertThat(set.restBetweenRound(), is(60L));
}