为 List 创建并注册一个类型适配器。创建它看起来像这样:
private final TypeAdapter<List<User>> listOfUsersTypeAdapter = new TypeAdapter<List<User>>() {
@Override public void write(JsonWriter out, List<User> value) throws IOException {
out.beginArray();
for (User user : value) {
out.value(user.id);
}
out.endArray();
}
@Override public List<User> read(JsonReader in) throws IOException {
in.beginArray();
List<User> result = new ArrayList<User>();
while (in.hasNext()) {
User user = new User();
user.id = in.nextString();
}
in.endArray();
return result;
}
}.nullSafe();
并在创建Gson
对象时注册它:
Gson gson = new GsonBuilder()
.registerTypeAdapter(new TypeToken<List<User>>() {}.getType(), listOfUsersTypeAdapter)
.create();
I haven't tested this but it should work. Note that when you deserialize your users won't have any of their friends or matches fields filled in. You can reconstruct that from the graph in a post-processing step. Or use GraphAdapterBuilder to do it automatically.