0
餘米試圖序列休眠對象到JSON的使用GSON library.I的連載休眠對象到JSON不得不實施自定義類型適配器在這種情況下,因爲GSON不能序列在HibernateProxy對象正常的方式。我試圖實現TypeAdapter,因爲我可以使用任何對象類型而無需修改它。關於使用GSON
這裏是我TypeAdapter類:
public class CustomTypeAdapter implements JsonSerializer<Object> {
@Override
public JsonElement serialize(Object object, Type type, JsonSerializationContext jsc) {
JsonObject jsonObject = new JsonObject();
try {
Map<String, String> properties = BeanUtils.describe(object);
//org.apache.commons.beanutils
for (Map.Entry<String, String> entry : properties.entrySet()) {
jsonObject.addProperty(entry.getKey(), entry.getValue());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return jsonObject;
}
}
但我有問題的內部對象不會與此實現序列化。它只是返回對象的地址(產品@ 54554356)
List<ProductHasSize> phsList = s.createCriteria(ProductHasSize.class, "phs")
.createAlias("phs.product", "product")
.add(Restrictions.eq("product.id", 1))
.list();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.registerTypeAdapter(ProductHasSize.class, new CustomTypeAdapter()).create();
String element = gson.toJson(phsList);
response.getWriter().write(element);
電流輸出-放:
[{"product":"[email protected]","size":"[email protected]","price":"1250.0","qnty":"20","id":"1","class":"class com.certus.dbmodel.ProductHasSize"},{"product":"[email protected]","size":"[email protected]455a","price":"1300.0","qnty":"5","id":"2","class":"class com.certus.dbmodel.ProductHasSize"}]
在此先感謝。