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

Jackson ObjectMapper gives error with recursive datatype

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

如果我删除列表 属性 它工作正常,所以问题出在递归上。

有没有办法告诉 ObjectMapper 此递归以便它正确处理?有没有其他方法可以生成此 json 模式?

DTNodo class

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 已弃用。您需要改用 the new JSON schema module

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