2017-01-10 30 views
2

我有pojo DTNodo,它具有遞歸屬性List<DTNodo>。 當我嘗試使用jackson生成json模式時,我得到一個java.lang.StackOverflowError異常。Jackson ObjectMapper給出了遞歸數據類型錯誤

如果我刪除列表屬性它工作正常,所以問題與遞歸。

有沒有辦法告訴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(); 
    } 
} 
+0

傑克遜的版本? – dnault

+1

現在我正在使用com.fasterxml.jackson.core 2.8.5,之前我使用的是org.codehaus.jackson 1.9.13。兩人都給了我同樣的錯誤。 – aleviera

回答

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

完美工作。謝謝! – aleviera

0

有出沒有簡單的方法。 您應該儘量避免序列化一次性導致pojo中的引用循環的屬性。

可以實現類似下面的例子(對象序列化作爲參考),但你必須確保客戶端應用程序能夠反序列化:

{ 「ID」:「1」, 「名稱「: 「約翰」, 「朋友」: { 「ID」: 「2」, 「名」: 「賈裏德」, 「朋友」: { 「$ REF」: 「1」 } ] } }

我會做的是seralize父對象沒有導致循環(@JsonIgnore)的屬性。然後序列化其餘部分,並使客戶端應用程序重新組成對象。

您可以使用@JsonManagedReference,@JsonBackReference 更多信息:http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

+0

雖然這是使用循環引用序列化對象的好建議,但OP在* schema generation *期間詢問無限遞歸*,這是一個不同的問題。 – dnault

相關問題