RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 823280
Accepted
Alex
Alex
Asked:2020-05-04 21:57:45 +0000 UTC2020-05-04 21:57:45 +0000 UTC 2020-05-04 21:57:45 +0000 UTC

列表到 Json 序列化

  • 772

大家好。并立即问题:如何将 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

java
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Alex
    2020-05-05T15:30:55Z2020-05-05T15:30:55Z

    据我了解,图书馆Gson也不喜欢实体中的双向关系。在对抗实体或这些实例中的双向关系时:

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

    并且可能:

    Infinity Exception
    

    顺便说一句,这更清楚地表达了问题的本质!

    帮助过我:

    1. 用 替换库Gson,Jackson即:

      <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-core-asl</artifactId>
          <version>1.9.13</version>
      </dependency>
      
    2. 使用注释@JsonIgnore或一对@JsonBackReferenceand ,您可以在这里@JsonManagedReference阅读它们,这里

      • @JsonManagedReference常规序列化:
      • @JsonIgnore,@JsonBackReference序列化异常;

    我是这样申请的:

    车类

    @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 = new CarType();
        private Client client = new Client();
        private List<Order> orderList = new ArrayList<>();
    
        @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")
        @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")
        @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")
        @JsonBackReference
        @ManyToOne(fetch = FetchType.LAZY, optional = true)
        @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")
        @JsonBackReference
        @ManyToOne(fetch = FetchType.EAGER, 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;
        }
    
        @JsonProperty("orders")
        @JsonManagedReference
        //@Transient
        @OneToMany(fetch = FetchType.EAGER, mappedBy = "car")
        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, %d, %d, %s", id, name, number, carType.getId(), client.getId(), orderList);
        }
    
        /**
         * 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();
        }
    
    }
    

    CarType 类

    @Entity
    @Table(name = "CarType")
    public class CarType implements Serializable, Storable {
        private static final long serialVersionUID = 1000000000000112L;
        public static final String GET_BY_TYPE = "select e from CarType e where e.type = ?1";
    
        private Long id;
        private String type;
        private List<Car> carList = new ArrayList<>();
        private List<Price> prices = new ArrayList<>();
    
        @Id
        @GeneratedValue(generator = "increment")
        @GenericGenerator(name = "increment", strategy = "increment")
        @Column(name = "car_type_id", nullable = false)
        @Override
        public Long getId() {
            return id;
        }
    
        @Override
        public void setId(Long id) {
            this.id = id;
        }
    
        @JsonProperty("type")
        @Size(max = 15, message = "{size.field}")
        @Column(name = "type", nullable = true, insertable = true, updatable = true, length = 15)
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
    
        @JsonProperty("cars")
        @JsonManagedReference
        //@Transient
        @OneToMany(mappedBy = "carType")
        public List<Car> getCarList() {
            return carList;
        }
    
        public void setCarList(List<Car> carList) {
            this.carList = carList;
        }
    
    
    
        @JsonProperty("prices")
        @JsonManagedReference
        //@Transient
        @OneToMany(mappedBy = "type")
        public List<Price> getPrices() {
            return prices;
        }
    
        public void setPrices(List<Price> prices) {
            this.prices = prices;
        }
    
        @Override
        public String toString() {
            return String.format("%d, %s, %s, %s", id, type, carList, prices);
        }
    
        /**
         * The method Copy the object of the carList type
         *
         * @param u - the object of the carList type
         */
        public void copy(CarType u) {
            this.setCarList(u.getCarList());
            this.setPrices(u.getPrices());
            this.setType(u.getType());
        }
    
        /**
         * Override hashCode for correct work equals
         *
         * @return hashCode
         */
        @Override
        public int hashCode() {
            return new HashCodeBuilder()
                    .append(this.carList)
                    .append(this.prices)
                    .append(this.type)
                    .toHashCode();
        }
    
        /**
         * Compares of the carList type
         *
         * @param obj for compare
         * @return true if equals
         */
        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof CarType))
                return false;
            if (obj == this)
                return true;
    
            CarType u = (CarType) obj;
            return new EqualsBuilder()
                    .append(this.carList, u.carList)
                    .append(this.prices, u.prices)
                    .append(this.type, u.type)
                    .isEquals();
        }
    
    }
    

    它帮助了我——我希望它也能帮助你。

    • 1

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5