的我有這樣的代碼片段:GSON轉換,而不是到的LinkedHashMap我的對象
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我的實體對象不再是實體類型,但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;
}
}
您使用的是Gson 2.1嗎? – 2012-04-09 13:56:55