当我们使用gson 转对象时,并且这个对象中有一些属性是懒加载时如

@Entity
@Table(name = "user")
public class User {
    @Id
    @Column(columnDefinition="varchar(255)")
    @GeneratedValue(generator="idGenerator")
    @GenericGenerator(name="idGenerator", strategy="uuid")
    private String userId;
    private String userName;
    private String nickName;
    private String passWord;
    private String phoneNumber;

    @ManyToOne(cascade = {CascadeType.ALL},optional = true,fetch = FetchType.LAZY)
    @JoinColumn(name = "enterprise_Id")
    private EnterpriseInfo enterpriseInfo;
    }

会出现Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?

原因是:

hibernate采取懒加载的方式查询数据库,也就是只有用到了才去查真正的数据,用不到的话只是返回一个代理对象,gson识别不了代理对象,所以没法转换.

解决办法:

1.新建一个类,并继承TypeAdapter

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.hibernate.Hibernate;
import org.hibernate.proxy.HibernateProxy;

import java.io.IOException;

/**
 * @ClassName HibernateProxyTypeAdapter
 * @Description 解决gson转换中对象有懒加载情况报错:
 * @Author PC
 * @Date 2018/10/29 10:23
 **/
public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {

    public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            return (HibernateProxy.class.isAssignableFrom(typeToken.getRawType())? (TypeAdapter) new HibernateProxyTypeAdapter(gson):null);
        }
    };

    private final Gson context;
    private HibernateProxyTypeAdapter(Gson gson){
        this.context = gson;
    }
    @Override
    public void write(JsonWriter jsonWriter, HibernateProxy hibernateProxy) throws IOException {
        if (hibernateProxy==null){
            jsonWriter.nullValue();
            return;
        }
        Class<?> baseType = Hibernate.getClass(hibernateProxy);
        TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
        Object unproxiedValue = ((HibernateProxy) hibernateProxy).getHibernateLazyInitializer()
                .getImplementation();
        delegate.write(jsonWriter,unproxiedValue);
    }

    @Override
    public HibernateProxy read(JsonReader jsonReader) throws IOException {
        throw new UnsupportedOperationException("Not support");
    }
}

2.构建gson对象

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd")
      .registerTypeAdapterFactory( HibernateProxyTypeAdapter.FACTORY).create() ; 

3.完成.

参考别人的博客并加以整理.

Copyright © 2024 守护锁链
Powered by .NET 9.0 on Kubernetes