Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Json(fasterxml)堆栈溢出异常_Java_Json_Spring_Data Binding_Fasterxml - Fatal编程技术网

Java Json(fasterxml)堆栈溢出异常

Java Json(fasterxml)堆栈溢出异常,java,json,spring,data-binding,fasterxml,Java,Json,Spring,Data Binding,Fasterxml,当尝试序列化一个类别时,我得到一个stackoverflow 例外情况 @RequestMapping(value="/{id}", method=RequestMethod.GET) public ResponseEntity<Category> get(@PathVariable("id") long categoryId) { Category c = service.getCategoryRepository().ReadValue(categoryId);

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

例外情况

@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);
}
警告:StandardWrapperValve[dispatcher]:的Servlet.service() servlet dispatcher在处引发异常java.lang.StackOverflower java.lang.ClassLoader.defineClass1(本机方法)位于 java.lang.ClassLoader.defineClass(ClassLoader.java:760)位于 org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.findClass(BundleWiringImpl.java:2279) 在 org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1501) 在 org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75) 在 org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955) 位于java.lang.ClassLoader.loadClass(ClassLoader.java:357) com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:660) 在 com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152) 在 com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100) 在 com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21) 在 serialize(AsArraySerializerBase.java:183) 在 com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541) 在 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644) 在 com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)

Category.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();
} 
}
@实体
公共类类别实现DataObject,可序列化{
@身份证
@生成值
私人长id;
私有字符串标题;
私有字符串描述;
@ManyToOne@JsonIgnore
私人类别家长;
@凌驾
公共长getId(){
返回id;
}
@凌驾
公共无效集合id(长id){
this.id=id;
}
公共字符串getTitle(){
返回标题;
}
公共无效集合标题(字符串标题){
this.title=标题;
}
公共字符串getDescription(){
返回说明;
}
公共void集合描述(字符串描述){
this.description=描述;
}
公共类别getParent(){
return null;//返回父级;
}
公共无效集合父对象(类别父对象){
//this.parent=parent;
}
公共布尔值isMainCategory()
{
return true;//返回this.parent==null;
}
/**
*返回主类别位于索引0上的父类别链
*@返回类别链
*/
公共列表getParentChain()
{
列表猫=新的ArrayList();
类别电流=此;
而(!current.isMainCategory())
{
cats.add(当前);
current=current.getParent();
}
cats.add(当前);
收藏。反面(猫);
返回猫;
}
@凌驾
公共字符串toString()
{
返回此.title;
}
@凌驾
公共布尔等于(对象o)
{
如果(!(o instanceof Category))返回false;
c类=(o类);
返回c.title.equals(此标题);
}
@凌驾
公共int hashCode()
{
返回super.hashCode();
} 
}
休息控制器功能

@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);
}
@RequestMapping(value=“/{id}”,method=RequestMethod.GET)
public ResponseEntity get(@PathVariable(“id”)long categoryId)
{
c类=service.getCategoryRepository().ReadValue(categoryId);
如果(c==null)
返回新的ResponseEntity(未找到HttpStatus.NOT_);
返回新的响应状态(c,HttpStatus.OK);
}
注意

即使在我替换
时返回新的ResponseEntity(c,HttpStatus.OK)返回新的响应属性(新类别(),HttpStatus.OK)我将获得一个stackoverflow列表,其中没有任何字段包含值


它可以与我的其他类一起工作,只有这个类会导致堆栈溢出。

如果您评论
私有类别父类,可能会出现这种情况您将不会有堆栈溢出。我在一个循环依赖的项目中也遇到了同样的问题

解决此问题的最佳方法是使用父级的id,而不是类,如:

private Long parentId;
编辑:


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

当然,
@JsonIgnore
完成了这项工作。但如果我们在JSON输出中需要忽略字段呢

解决方案非常简单

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

@JsonBackReference
位于关系的另一侧(其中放置了
@OneToMany


就这样。不再有递归循环。

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

在类上添加以下注释

@JsonIdentityInfo(
      generator = ObjectIdGenerators.PropertyGenerator.class, 
      property = "id")
另一种方法是在集合@JsonManagedReference上注释前进方向,@JsonBackReference.注释映射中的后退方向

例如:

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

public class Address{
    @JsonBackReference
    @ManyToOne
    @JoinColumn
    User user;
}
公共类用户{
@JsonManagedReference
@OneToMany(mappedBy=“用户”)
Set s=新的Hashset();
}
公共课堂演讲{
@JsonBackReference
@许多酮
@连接柱
用户;
}

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

@JsonIgnore
添加到JPA实体中的每个
@OneToMany(mappedBy=“xxxx”)

JsonIgnore来自
jackson注释

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

com.fasterxml.jackson.core
杰克逊注释
2.10.0
JPA实体示例:

package model;

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

import com.fasterxml.jackson.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;
    }

}
包模型;
导入java.io.Serializable;
导入javax.persistence.*;
导入javax.xml.bind.annotation.XmlRootElement;
导入com.fasterxml.jackson.anno