大家好。并立即问题:如何将 List 转换为 Json
如果我将一个Car 对象转换为 Json-obj,那么一切都很好
Car cars = carSrv.getById(1);
Gson gson = new GsonBuilder().create();
String jse = gson.toJson(cars);
尝试使用列表执行此操作时(Json 中的列表)
List<Car> cars = carSrv.getAll();
Gson gson = new GsonBuilder().create();
String jse = gson.toJson(cars);
执行崩溃:
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:76)
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:69)
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:112)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
at com.google.gson.Gson.toJson(Gson.java:661)
at com.google.gson.Gson.toJson(Gson.java:640)
at com.google.gson.Gson.toJson(Gson.java:595)
at com.google.gson.Gson.toJson(Gson.java:575)
...
我正在使用 Gson 库:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
在网上的某个地方,我找到了一个带有类型指示的解决方案:
List<Car> cars = carSrv.getAll();
Gson gson = new GsonBuilder().create();
Type listType = new TypeToken<List<Car>>() {}.getType();
String jse = gson.toJson(cars, listType);
没有帮助!相同的ekzepshn
我在这里找到了另一个解决方案和很多重复项:) 不过,我认为这里的问题不在于休眠,而在于序列化
List<Car> cars = carSrv.getAll();
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY)
.create();
String jse = gson.toJson(cars);
我从示例中获取了 HibernateProxyTypeAdapter 类。
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);
}
}
没有帮助!查看例外:
2018-мая-04 16:33:00.829 ERROR [http-nio-8080-exec-8] o.s.b.w.s.ErrorPageFilter - Forwarding to error page from request [/aes/by/id] due to exception [null]
java.lang.StackOverflowError: null
at com.google.gson.internal.bind.TypeAdapters$11.write(TypeAdapters.java:317)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:97)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
at ua.avk.carwash.adapter.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:54)
at ua.avk.carwash.adapter.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:19)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968)
这是 Car 类本身,以防万一:
@JsonInclude(JsonInclude.Include.NON_NULL)
@Entity
@Table(name = "Car")
public class Car implements Serializable, Storable {
private static final long serialVersionUID = 1000000000000111L;
public static final String GET_BY_NAME = "select e from Car e where e.name = ?1";
public static final String GET_BY_TYPE = "select e from Car e where e.carType = ?1";
public static final String GET_BY_NUMBER = "select e from Car e where e.number = ?1";
public static final String GET_BY_CLIENT = "select e from Car e where e.client = ?1";
private Long id;
private String name;
private String number;
private CarType carType;
private Client client;
private List<Order> orderList = new ArrayList<>();
@JsonView(Views.User.class)
@JsonProperty("id")
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "car_id", nullable = false)
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@JsonProperty("name")
@JsonView(Views.User.class)
@Size(max = 50, message = "{size.field}")
@Column(name = "name", nullable = true, insertable = true, updatable = true, length = 50)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonProperty("number")
@JsonView(Views.User.class)
@Size(max = 8, message = "The car number must be {min} to {max} characters in length.")
@Column(name = "number", nullable = true, insertable = true, updatable = true, length = 8)
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@JsonProperty("cartype")
@JsonView(Views.User.class)
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "type_id", nullable = true, insertable = true, updatable = true)
public CarType getCarType() {
return carType;
}
public void setCarType(CarType carType) {
this.carType = carType;
}
@JsonProperty("client")
@JsonView(Views.User.class)
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "client_id", nullable = true, insertable = true, updatable = true)
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
//@Transient
@JsonProperty("orders")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonView(Views.Admin.class)
@OneToMany(fetch = FetchType.LAZY, mappedBy = "car")
//@Column(name = "order_id")
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
@Override
public String toString() {
return String.format("%d, %s, %s, %s, %s;", id, name, number, carType, client);
}
/**
* The method Copy the object of the car
*
* @param u - the object of the car
*/
public void copy(Car u) {
this.setClient(u.getClient());
this.setOrderList(u.getOrderList());
this.setName(u.getName());
this.setNumber(u.getNumber());
this.setCarType(u.getCarType());
}
/**
* Override hashCode for correct work equals
*
* @return hashCode
*/
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(this.client)
.append(this.name)
.append(this.number)
.append(this.carType)
.toHashCode();
}
/**
* Compares of the car
*
* @param obj for compare
* @return true if equals
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Car))
return false;
if (obj == this)
return true;
Car u = (Car) obj;
return new EqualsBuilder()
.append(this.client, u.client)
.append(this.name, u.name)
.append(this.number, u.number)
.append(this.carType, u.carType)
.isEquals();
}
}
问题:在这种情况下如何将 List 转换为 Json
据我了解,图书馆
Gson
也不喜欢实体中的双向关系。在对抗实体或这些实例中的双向关系时:并且可能:
顺便说一句,这更清楚地表达了问题的本质!
帮助过我:
用 替换库
Gson
,Jackson
即:使用注释
@JsonIgnore
或一对@JsonBackReference
and ,您可以在这里@JsonManagedReference
阅读它们,这里@JsonManagedReference
常规序列化:@JsonIgnore
,@JsonBackReference
序列化异常;我是这样申请的:
车类
CarType 类
它帮助了我——我希望它也能帮助你。