2016-01-21 42 views
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"}] 

在此先感謝。

回答

0

BeanUtils.describe沒有提供足夠的信息。如果所有類型都是原始的,那將會很好。

您必須獨立序列化每個屬性。對於不是原始類型的字段,請將它們序列化。您還必須爲實際類型創建適配器,以便您可以訪問其屬性。

public class CustomTypeAdapter implements JsonSerializer<ProductHasSize> { 

@Override 
public JsonElement serialize(ProductHasSize phs, 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(); 
// } 
    jsonObject.addProperty("price", phs.getPrice()); 
    jsonObject.addProperty("quantity", phs.getQuantity()); 
    JsonElement jsonProduct = jsc.serialize(phs.getProduct()); 
    jsonObject.add("product", jsonProduct); 
    JsonElement jsonSize = jsc.serialize(phs.getSize()); 
    jsonObject.add("size", jsonSize); 

    return jsonObject; 
    } 

} 

這個頁面有一個很好的介紹:http://www.javacreed.com/gson-serialiser-example/