繁体   English   中英

Jackson ObjectMapper给出了递归数据类型的错误

[英]Jackson ObjectMapper gives error with recursive datatype

我有pojo DTNodo ,它有一个递归属性List<DTNodo> 当我尝试使用jackson生成json模式时,我得到一个java.lang.StackOverflowError异常。

如果我删除List属性它工作正常,所以问题在于递归。

有没有办法告诉ObjectMapper这个递归,所以它正确处理它? 有没有其他方法来生成这个json架构?

DTNodo类

public class DTNodo implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer idNodo;
    private String codigo;
    private String descripcion;
    private String detalle;
    private Integer orden;

    private List<DTNodo> hijos;

    public Integer getIdNodo() {
        return idNodo;
    }

    public void setIdNodo(Integer idNodo) {
        this.idNodo = idNodo;
    }

    public String getCodigo() {
        return codigo;
    }

    public void setCodigo(String codigo) {
        this.codigo = codigo;
    }

    public String getDescripcion() {
        return descripcion;
    }

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

    public String getDetalle() {
        return detalle;
    }

    public void setDetalle(String detalle) {
        this.detalle = detalle;
    }

    public Integer getOrden() {
        return orden;
    }

    public void setOrden(Integer orden) {
        this.orden = orden;
    }

    public List<DTNodo> getHijos() {
        return hijos;
    }

    public void setHijos(List<DTNodo> hijos) {
        this.hijos = hijos;
    }

}

我用来生成jsonschema的代码

public static String getJsonSchema(Class<?> clazz) {
    ObjectMapper mapper = new ObjectMapper();
    JsonSchema schema;
    try {
        schema = mapper.generateJsonSchema(clazz);

        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);

    } catch (IOException e) {
        return "Error al generar JsonSchema: " + e.getMessage();
    }
}

不推荐使用ObjectMapper.generateJsonSchema。 您将要使用新的JSON模式模块

com.fasterxml.jackson.module:jackson-module-jsonSchema:${jacksonVersion}到您的项目中并生成如下架构:

ObjectMapper mapper = new ObjectMapper();
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
JsonSchema schema = schemaGen.generateSchema(clazz);
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);

确保从正确的包中导入现代JsonSchema:

import com.fasterxml.jackson.module.jsonSchema.JsonSchema;

没有简单的方法。 您应该尽量避免序列化导致POJO中的引用循环的属性。

您可以实现类似以下示例(对象序列化为引用),但您必须确保客户端应用程序能够反序列化它:

{
   "id": "1",
   "name": "John",
   "friends": [
      {
          "id": "2",
          "name": "Jared",
          "friends": [
                    {
                        "$ref": "1"
                    }
                ]
      }
}

我要做的是序列化父对象,而没有导致循环的属性( @JsonIgnore )。 然后序列化其余部分并使客户端应用程序重新组合对象。

您可以使用@JsonManagedReference@JsonBackReference

更多信息: http//www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM