我有以下代码尝试序列化 DT_RowId。事实上,我将创建一个具有 DT_RowId 变量的抽象类。扩展抽象类的任何其他实体也应该序列化该字段。课程如下:
实体.java
public class Entity extends PersistentObject {
protected long creationTime;
protected boolean enabled;
protected long id; // from PersistentObject
protected long loginDuration;
protected boolean online;
protected String userName;
protected long DT_RowId;// from PersistentObject
}
EntityJsonSerializer.java
import java.lang.reflect.Type;
import com.google.gson.*;
public class EntityJsonSerializer implements JsonSerializer<Entity> {
@Override
public JsonElement serialize(Entity entity, Type typeOfSrc, JsonSerializationContext context) {
entity.DT_RowId = entity.id;
Gson gson = new Gson();
return gson.toJsonTree(entity);
}
}
JSONTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.gson.*;
public class JSONTest {
@Test
public final void testSerializeWithDTRowId() {
Entity entity = new Entity();
entity.creationTime = 0;
entity.enabled = true;
entity.id = 1;
entity.loginDuration = 0;
entity.online = false;
entity.userName = "someone";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Entity.class, new EntityJsonSerializer());
Gson gson = builder.create();
String json = gson.toJson(entity);
String expectedJson = "{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"userName\":\"someone\",\"DT_RowId\":1}";
assertEquals(expectedJson, json);
}
}
如何使上述代码通用,以便任何扩展抽象类的类都将 DT_RowId 序列化?