我有一个实体:
@Entity
public class User {
@PrimaryKey
private int uId;
private String uName;
private ArrayList<String> uPets = new ArrayList<>();
public User() {}
public User(int id, String name, List<String> pets){
this.uId = id;
this.uName = name;
this.uPets.addAll(pets);
};
//getters setters removed for brevity
}
类型转换器是:
public class Converters {
@TypeConverter
public static ArrayList<String> fromString(String value) {
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String fromArrayLisr(ArrayList<String> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
}
数据库类包含一行介绍类型转换器的行:
@Database (entities = {User.class},version = 1)
@TypeConverters({Converters.class})
public abstract class UserDB extends RoomDatabase {
public abstract UserDAO userDAO();
}
因此,上述代码在将数据存储到数据库表方面都可以正常工作。但是,我现在想将代表用户数据的一些JSON数据解析为User
类。 Json格式如下:
{ "uId": "123",
"uName": "John Doe",
"uPets": [ "cat", "dog", "fish", "pizza"]
}
当我尝试使用Gson解析上述Json数据时,出现com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at path $.users[0].uPets
我尝试将类型适配器添加到我的GsonBuilder中,例如:
builder.registerTypeAdapter(ArrayList.class, new Converters())
但这也给我一个错误:
java.lang.IllegalArgumentException
at com.google.gson.internal.$Gson$Preconditions.checkArgument($Gson$Preconditions.java:46)
at com.google.gson.GsonBuilder.registerTypeAdapter(GsonBuilder.java:497)
...
感谢任何帮助,在此先感谢
答案 0 :(得分:0)
您的问题是在uPets arrayList中使用了':
将“在披萨中”更改为“
'pizza”->“ pizza”