如何让Gson使用Externalizables?

时间:2016-01-30 15:58:57

标签: java gson

我有以下User.class(仅举例):

public class User implements Externalizable {

    int id;
    String username;
    public User(String username, int id) {
        this.username = username;
        this.id = id;
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {}

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(id +"_" + username);
    }

}

这是我保存用户的方式:

 Gson testson = new GsonBuilder().setPrettyPrinting().create();
 FileWriter writer = new FileWriter(file);
 Map<String, User> userStorage = new HashMap<>();
 userStorage.put("test_user_1", new User("TestUser1", 213));
 userStorage.put("test_user_2", new User("TestUser2", 999));
 userStorage.put("test_user_3", new User("TestUser3", 3));
 writer.write(testson.toJson(userStorage));
 writer.close();

输出文件如下所示:

{
  "test_user_3": {
    "id": 3,
    "username": "TestUser3"
  },
  "test_user_1": {
    "id": 213,
    "username": "TestUser1"
  },
  "test_user_2": {
    "id": 999,
    "username": "TestUser2"
  }
}

根据我的预期:

{
  "test_user_3": "3_TestUser3",
  "test_user_1": "213_TestUser1",
  "test_user_2": "999_TestUser2"
}

如果我Gson忽略idusernametransient@Expose功能),结果就会如此:

{
  "test_user_3": {},
  "test_user_1": {},
  "test_user_2": {}
}

所以我的问题是:如何让Gson使用我覆盖的Externalizable方法?是GsonBuilder().registerTypeAdapter()用于此吗?

1 个答案:

答案 0 :(得分:1)

你做不到。但你可以写一个custom User serializer

public class UserSerializer implements JsonSerializer<User> {
    @Override
    public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.id + "_" + src.username);
    }
}

并配置Gson实例以使用用户类型的序列化程序:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(User.class, new UserSerializer())
        .create();