繁体   English   中英

关于使用Gson将休眠对象序列化为json

[英]Regarding serialize hibernate object to json using Gson

我试图使用Gson库将休眠对象序列化为json。在这种情况下,我必须实现自定义类型适配器 ,因为GSon无法以正常方式序列化HibernateProxy对象。我试图实现TypeAdapter,因为我可以与任何类型的适配器一起使用对象类型而不修改它。

这是我的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;
    }

}

但是我遇到的问题是内部对象不会通过此实现序列化。 它只是返回对象的地址。(Product @ 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":"com.certus.dbmodel.Product@54554356","size":"com.certus.dbmodel.Size@215a88a","price":"1250.0","qnty":"20","id":"1","class":"class com.certus.dbmodel.ProductHasSize"},{"product":"com.certus.dbmodel.Product@54554356","size":"com.certus.dbmodel.Size@2eab455a","price":"1300.0","qnty":"5","id":"2","class":"class com.certus.dbmodel.ProductHasSize"}]

提前致谢。

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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM