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

问题描述 投票:3回答:2

我有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();
    }
}
java json jackson jsonschema
2个回答
2
投票

不推荐使用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;

0
投票

没有简单的方法。您应该尽量避免序列化导致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

© www.soinside.com 2019 - 2024. All rights reserved.