主要原因:转成json对象bean中包含另一个bean,这是由于表中有外键,当获取的实体对象还在hibernate代理的时候,使json中对象中包含另一个对象,转成json时出错。调用下面的公用方法,可以实现正常转json
public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {
public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return (HibernateProxy.class.isAssignableFrom(type.getRawType()) ? (TypeAdapter<T>) new HibernateProxyTypeAdapter(gson) : null);
}
};
private final Gson context;
private HibernateProxyTypeAdapter(Gson context) {
this.context = context;
}
@Override
public HibernateProxy read(JsonReader in) throws IOException {
throw new UnsupportedOperationException("Not supported");
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void write(JsonWriter out, HibernateProxy value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
// Retrieve the original (not proxy) class
Class<?> baseType = Hibernate.getClass(value);
// Get the TypeAdapter of the original class, to delegate the serialization
TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
// Get a filled instance of the original class
Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()
.getImplementation();
// Serialize the value
delegate.write(out, unproxiedValue);
}
}
调用上面的方法:
/**
* 要转换成json的对象中不全是值属性,还包含了引用对象
* @param obj:list集合
*/
public static void returnJsonByObjectForHaveObject(Object obj){
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY)
.create();
String json = gson.toJson(obj);
System.out.println(json);
HttpServletResponse response=ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(writer != null){
writer.close();
}
}
}
输出的json:
[{"id":5,"appUser":{"userId":7,"name":"admin","password":"123456","sex":"男","phone":"13888888888"},"type":"最新资讯","code":"zxzx","content":"搞得好好干吧","time":"Mar 25, 2017 1:16:22 PM"},{"id":6,"appUser":{"userId":6,"name":"Johnny","password":"123456","sex":"女","phone":"15988194823","modifyTime":"Feb 22, 2017 1:59:50 PM","manageAddress":"D:\\Pictures\\15988194823.jpg"},"type":"点厨消息","code":"dcxx","content":"发vfhgn","time":"Mar 2, 2017 1:16:26 PM"}]