简体   繁体   English

使用 GSon 将休眠对象转换为 json

[英]converting hibernate objects to json using GSon

Im trying to convert a collection (obtained from Hibernate) to json string using Gson for use in my restful service.我正在尝试使用 Gson 将集合(从 Hibernate 获得)转换为 json 字符串,以便在我的宁静服务中使用。 But, the service is giving me http 500 error.但是,该服务给了我 http 500 错误。

My code is as under:我的代码如下:

@GET
@Path("/getScheduleLookUp")
@Produces(MediaType.APPLICATION_JSON)
public String getScheduleLookUp() throws IOException {
    ScheduleLookupDAO lookupDAO = new ScheduleLookupDAO();
    return new Gson().toJson(lookupDAO.getAllScheduleLookUps());
}

The hibernate list which is returned after querying the DB returns classname with some garbage value attached to it, may be because of lazy loading by Hibernate.I tried by turning lazy loading off also, but ended up with the same result.查询 DB 后返回的休眠列表返回带有一些垃圾值的类名,可能是因为 Hibernate 延迟加载。我也尝试关闭延迟加载,但最终得到相同的结果。 My class structure is somewhat like this我的班级结构有点像这样

public class ScheduleLookup extends BaseModel {

private static final long serialVersionUID = -2561410864465885712L;

private Integer scheduleId;
private String scheduleName;
private ClientLookup clientLookup;
private String description;
private Route route;
private String routeName;
private Double estimatedDuration;
private Double calculatedDuration;
private UserLookup createdBy;
private Date createdAt;
private UserLookup lastUpdatedBy;
private Date lastUpdatedAt;
private Boolean delFlag;
private UserLookup deletedBy;
private Date deletedAt;
private Boolean isSkipped;
private Integer daySpan;

Now when i debugged it , i found that the returned list had references of ClientLookup as ClientLookup$$Enhance... because of which is causing the problem.I tried to remove the proxies also but didn help.现在,当我调试它时,我发现返回的列表将 ClientLookup 引用为 ClientLookup$$Enhance...因此导致了问题。我也尝试删除代理,但没有帮助。 This is what I had tried to remove the proxy (found at one SO results)这就是我试图删除代理的内容(在一个 SO 结果中找到)

public static <T> T initializeAndUnproxy(T entity) {
    if (entity == null) {
        throw new 
           NullPointerException("Entity passed for initialization is null");
    }

    Hibernate.initialize(entity);
    if (entity instanceof HibernateProxy) {
        entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                .getImplementation();
    }

    return entity;
}

Error trace is as under :错误跟踪如下:

java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:67)
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ArrayTypeAdapter.write(ArrayTypeAdapter.java:93)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapter.java:107)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson.toJson(Gson.java:593)
at com.google.gson.Gson.toJson(Gson.java:572)
at com.google.gson.Gson.toJson(Gson.java:527)
at com.google.gson.Gson.toJson(Gson.java:507)
at com.pcs.bpems.services.SchedulesService.getScheduleLookUp(SchedulesService.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1480)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1411)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1360)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1350)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

I had also added lazy="no-proxy" in hbm file but to no avail我还在 hbm 文件中添加了 lazy="no-proxy" 但无济于事

<class name="com.test.ScheduleLookup" table="schedule_lookup">
    <id name="scheduleId" type="java.lang.Integer">
        <column name="schedule_id" />
        <generator class="native" />
    </id>
    <many-to-one name="clientLookup"
        class="com.test.hibernate.models.ClientLookup" fetch="select" lazy="no-proxy">
        <column name="client_id" />
    </many-to-one>.....

Any help would be greatly appreciated!任何帮助将不胜感激!

A great answer to this question was provided here - Could not serialize object cause of HibernateProxy这里提供了这个问题的一个很好的答案 - 无法序列化 HibernateProxy 的对象原因

The recommended way is to use a TypeAdapter without manually unproxying every object.推荐的方法是使用 TypeAdapter 而无需手动取消代理每个对象。 Then you would register the TypeAdapter with Gson.然后你将使用 Gson 注册 TypeAdapter。

Try parsing through ObjectMapper as尝试通过ObjectMapper解析为

ScheduleLookupDAO lookupDAO = new ScheduleLookupDAO();
return new ObjectMapper().writeValueAsString(lookupDAO.getAllScheduleLookUps());

Create a new Object that has only attributes you want to convert to JSON.创建一个仅具有要转换为 JSON 的属性的新对象。 Then Map the hibernate object ( getAll() ) and map each object to ur new Object type.然后映射休眠对象( getAll() )并将每个对象映射到你的新对象类型。 Return a List of those converted objects.返回这些转换对象的列表。

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

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