java Json (fasterxml) stackoverflow 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31841666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:13:57  来源:igfitidea点击:

Json (fasterxml) stackoverflow exception

javajsonspringdata-bindingfasterxml

提问by Svexo

When trying to serialize a Category I get a stackoverflow.

当尝试序列化一个类别时,我得到了一个 stackoverflow。

Exception

例外

Warning: StandardWrapperValve[dispatcher]: Servlet.service() for servlet dispatcher threw exception java.lang.StackOverflowError at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:760) at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.findClass(BundleWiringImpl.java:2279) at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1501) at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75) at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at com.fasterxml.Hymanson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:660) at com.fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152) at com.fasterxml.Hymanson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100) at com.fasterxml.Hymanson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21) at com.fasterxml.Hymanson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183) at com.fasterxml.Hymanson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541) at com.fasterxml.Hymanson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644) at com.fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)

警告:StandardWrapperValve[dispatcher]:servlet 调度程序的 Servlet.service() 在 java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:760) 处抛出异常 java.lang.StackOverflowError org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.findClass(BundleWiringImpl.java:2279) 在 org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1501) 在 org.apache.Bmpl.feundlelix.framework在 org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955) 在 com.fasterxml 的 java.lang.ClassLoader.loadClass(ClassLoader.java:357) 上访问 $400(BundleWiringImpl.java:75)。 Hymanson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:660) 在 com。fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152) 在 com.fasterxml.Hymanson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100) 在 com.fasterxml.Hymanson.databind。 ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21) 在 com.fasterxml.Hymanson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183) 在 com.fasterxml.Hymanson.databind.ser.BeanPropertyWriter。 serializeAsField(BeanPropertyWriter.java:541) 在 com.fasterxml.Hymanson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644) 在 com.fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java: 152)databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100) 在 com.fasterxml.Hymanson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21) 在 com.fasterxml.Hymanson.databind.ser。 std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183) 在 com.fasterxml.Hymanson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541) 在 com.fasterxml.Hymanson.databind.ser.std.BeanSerializerBase.serializeFields( BeanSerializerBase.java:644) 在 com.fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100) 在 com.fasterxml.Hymanson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21) 在 com.fasterxml.Hymanson.databind.ser。 std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183) 在 com.fasterxml.Hymanson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541) 在 com.fasterxml.Hymanson.databind.ser.std.BeanSerializerBase.serializeFields( BeanSerializerBase.java:644) 在 com.fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)com.fasterxml.Hymanson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183) 在 com.fasterxml.Hymanson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541) 在 com.fasterxml.Hymanson.databind。 ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644) 在 com.fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)com.fasterxml.Hymanson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183) 在 com.fasterxml.Hymanson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541) 在 com.fasterxml.Hymanson.databind。 ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644) 在 com.fasterxml.Hymanson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)

Category.java

类别.java

@Entity
public class Category implements DataObject, Serializable {

    @Id
    @GeneratedValue 
    private Long id;
    private String title;
    private String description;

    @ManyToOne @JsonIgnore 
    private Category parent;


@Override
public long getId() {
    return id;
}

@Override
public void setId(long id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}
public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public Category getParent() {
   return null;//return parent;
}

public void setParent(Category parent) {
   // this.parent = parent;
}

public boolean isMainCategory()
{
   return true;// return this.parent == null;
}

/**
 * Returns the chain of parent categories with the main category on index 0
 * @return Chain of categories 
 */
public List<Category> getParentChain()
{

   List<Category> cats = new ArrayList<>();
    Category current = this;
    while(!current.isMainCategory())
    {
        cats.add(current);
        current = current.getParent();
    }
    cats.add(current);
    Collections.reverse(cats);
    return cats;
}

@Override
public String toString()
{
    return this.title;
}

@Override
public boolean equals(Object o)
{
    if(!(o instanceof Category))return false;
    Category c = (Category)o;

    return c.title.equals(this.title);
}

@Override
public int hashCode()
{
    return super.hashCode();
} 
}

Rest Controller function

休息控制器功能

@RequestMapping(value="/{id}", method=RequestMethod.GET)
public ResponseEntity<Category> get(@PathVariable("id") long categoryId)
{
    Category c  =  service.getCategoryRepository().ReadValue(categoryId);
    if(c == null)
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    return new ResponseEntity<>(c,HttpStatus.OK);
}

Note

笔记

Even when I replace return new ResponseEntity<>(c,HttpStatus.OK);with return new ResponseEntity<>(new Category(),HttpStatus.OK);I will get a stackoverflow whilist none of the fields contain a value.

即使我替换return new ResponseEntity<>(c,HttpStatus.OK);return new ResponseEntity<>(new Category(),HttpStatus.OK);我也会得到一个 stackoverflow whilist 没有任何字段包含值。

It works fine with my other classes it's only this class that causes a stackoverflow.

它适用于我的其他类,只有这个类会导致堆栈溢出。

采纳答案by JFPicard

Probably if you comment private Category parent;you will not have the StackOverflow. I've got the same problem in a project with circular dependencies.

可能如果您发表评论,private Category parent;您将不会拥有 StackOverflow。我在具有循环依赖项的项目中遇到了同样的问题。

The best way to solve this problem is to use the id of the parent instead of the Class like:

解决这个问题的最好方法是使用父类的 id 而不是类,如下所示:

private Long parentId;

Edit:

编辑:

The problem is with getParentChain()that is trying to be serialized. By adding @JsonIgnore before the method the problem was resolved.

问题getParentChain()在于它试图被序列化。通过在方法之前添加@JsonIgnore,问题得到解决。

回答by Rafal

Sure thing, @JsonIgnoredoes the job. But what if we need ignored field in our JSON output?

当然,@JsonIgnore做这项工作。但是如果我们需要在 JSON 输出中忽略字段怎么办?

The solution is very simple.

解决方法很简单。

We annotate our 'guilty' field by @JsonManagedReferenceannotation on the one side of our relation (which means our @ManyToManyannotation).

我们通过@JsonManagedReference在我们关系的一侧(这意味着我们的@ManyToMany注释)进行注释来注释我们的“有罪”字段。

And @JsonBackReferenceon the other side of relation (where @OneToManyhas been placed).

@JsonBackReference在关系的另一侧(@OneToMany已放置的位置)。

And that's it. No more recursive loops.

就是这样。没有更多的递归循环。

回答by Shamanth Ramesh

One annotation solves your problem.

一个注释可以解决您的问题。

Add following annotation on class.

在类上添加以下注释。

@JsonIdentityInfo(
      generator = ObjectIdGenerators.PropertyGenerator.class, 
      property = "id")

Other way is to annotate on Collections @JsonManagedReferencefor forward direction and @JsonBackReference.for backward direction in mapping.

另一种方法是在集合@JsonManagedReference上注释前向和@JsonBackReference。用于映射中的反向。

example:

例子:

public class User{
    @JsonManagedReference
    @OneToMany(mappedBy = "user")
    Set<Address> s = new Hashset<>();
}

public class Address{
    @JsonBackReference
    @ManyToOne
    @JoinColumn
    User user;
}

回答by Wesos de Queso

This is what i do to avoid this recursive hell.

这就是我为避免这种递归地狱所做的。

Add @JsonIgnoreto every single @OneToMany(mappedBy="xxxx")in your JPA Entities

添加@JsonIgnore@OneToMany(mappedBy="xxxx")JPA 实体中的每一个

JsonIgnore is from Hymanson-annotations

JsonIgnore 来自 Hymanson-annotations

    <!-- https://mvnrepository.com/artifact/com.fasterxml.Hymanson.core/Hymanson-annotations -->
    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-annotations</artifactId>
        <version>2.10.0</version>
    </dependency>

JPA Entity example:

JPA 实体示例:

package model;

import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.Hymanson.annotation.JsonIgnore;

import java.util.List;


/**
 * The persistent class for the categoria database table.
 * 
 */
@Entity
@NamedQuery(name="Categoria.findAll", query="SELECT c FROM Categoria c")
@XmlRootElement(name = "categoria")
public class Categoria implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="categoria_id")
    private int categoriaId;

    private String descripcion;

    @JsonIgnore
    //bi-directional many-to-one association to Establecimiento
    @OneToMany(mappedBy="categoria")
    private List<Establecimiento> establecimientos;

    public Categoria() {
    }

    public int getCategoriaId() {
        return this.categoriaId;
    }

    public void setCategoriaId(int categoriaId) {
        this.categoriaId = categoriaId;
    }

    public String getDescripcion() {
        return this.descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public List<Establecimiento> getEstablecimientos() {
        return this.establecimientos;
    }

    public void setEstablecimientos(List<Establecimiento> establecimientos) {
        this.establecimientos = establecimientos;
    }

    public Establecimiento addEstablecimiento(Establecimiento establecimiento) {
        getEstablecimientos().add(establecimiento);
        establecimiento.setCategoria(this);

        return establecimiento;
    }

    public Establecimiento removeEstablecimiento(Establecimiento establecimiento) {
        getEstablecimientos().remove(establecimiento);
        establecimiento.setCategoria(null);

        return establecimiento;
    }

}