我有这段代码:
public abstract class Repository<Entity extends BaseObject> {
...
public void readFromJson(){
String content = "JSON content here";
Gson gson = new Gson();
Type entityType = new TypeToken<JSONObject<Entity>>(){}.getType();
jsonObject = gson.fromJson(content, entityType);
for (Entity ent : jsonObject.getEntities()) ;
}
}
当我尝试使用foreach循环时,我的实体对象不再是Entity类型,而是LinkedHashMap类型,并且出现以下异常:java.lang.ClassCastException: java.util.LinkedHashMap无法转换为com.tranca.bookstore.domain.shared.BaseObject
这是由我创建的JSONObject类:
public class JSONObject<Entity> {
private List<Entity> entities = new ArrayList<Entity>();
private long lastId = -1;
public List<Entity> getEntities() {
return entities;
}
public void setEntities(List<Entity> entities) {
this.entities = entities;
}
public long getLastId() {
return lastId;
}
public void setLastId(long lastId) {
this.lastId = lastId;
}
public void incrementLastId() {
this.lastId++;
}
}
也许基础对象是相关的,所以我会在这里放置代码:
public abstract class BaseObject implements Serializable {
protected long id = (long) -1;
protected int version = 0;
protected BaseObject(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
gsonBuilder.enableComplexMapKeySerialization()
解决了我的问题。 - CrandellWS