2016-05-31 14 views
-1

JSON形式でツリー構造を保存してください。私はフィールドに対処する@JsonBackReference@JsonManagedReference注釈を使用しますが、インターフェイスに再帰を解決する方法を何のアイデアを持っていないJSONシリアライズで循環参照を解決するにはどうすればよいですか?

public class CustomASTNode implements ASTNode { 
    private final CustomNode node; // simple property 
    private final ASTNodeID id; // simple property 
    @JsonBackReference 
    private final ASTNode parent; // circular property! 
    @JsonManagedReference 
    private List<ASTNode> children = new ArrayList<>(); // circular property! 
    // more code 
} 

public interface ASTNode extends Iterable<ASTNode> { // ? 
    // more code 
} 

:私はfolowingコードに

ERROR 6444 --- [nio-8090-exec-1] o.a.c.c.C.[.[.[/]. [dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler processing failed; nested exception is java.lang.StackOverflowError] with root cause 

java.lang.StackOverflowError: null 
    at java.lang.Class.getGenericInterfaces(Class.java:912) ~[na:1.8.0_40] 
    at com.fasterxml.jackson.databind.type.TypeFactory._doFindSuperInterfaceChain(TypeFactory.java:1260) ~[jackson-databind-2.6.6.jar:2.6.6] 
    at com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(TypeFactory.java:1254) ~[jackson-databind-2.6.6.jar:2.6.6] 
    // more stacktrace here... 

を得ました。可能でしょうか、あるいはこれらのスニペットを書き直す必要がありますか?

+2

循環参照がある場合、それは木ではありません。 –

+0

@AndyTurnerはい、インターフェース定義( 'ASTNode extends Iterable ')の循環参照については、 'parent'と' children'フィールドを使って 'CustomASTNode'オブジェクトからツリーを構築しています。 –

+0

あなたのASTNodeのフォームはサイクルを持つグラフですか? – Pace

答えて

1

簡単な例は以下のようになりhttp://wiki.fasterxml.com/JacksonFeatureObjectIdentity

を見てみましょう:

Identifiable ob1 = new Identifiable(); 
ob1.value = 13; 
Identifiable ob2 = new Identifiable(); 
ob2.value = 42; 
// link as a cycle: 
ob1.next = ob2; 
ob2.next = ob1; 

シリアライズ:

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id") 
public class Identifiable 
{ 
    public int value; 

    public Identifiable next; 
} 

を、私たちは次のように、二つの値からなるサイクルを作成した場合使用:

String json = objectMapper.writeValueAsString(ob1); 

我々はJSONのためのシリアル化を次のようになるだろう:

{ 
    "@id" : 1, 
    "value" : 13, 
    "next" : { 
     "@id" : 2, 
     "value" : 42, 
     "next" : 1 
    } 
} 
+0

ありがとう、インターフェース定義から 'extends Iterable 'を削除した '@ JsonIdentityInfo'アノテーションは、問題を解決します。 –

関連する問題