Jackson confused with bidirectional one-to-many relationship

I'm using jackson 1.9.2 with Hibernate/Spring MVC through MappingJacksonHttpMessageConverter.
Jackson can not serialize bidirectional one-to-many relationship and makes an infinite loop.
The classes I'm using are :
  • Conversation which has a Set of SMS instances.
  • Each SMS instance has a Set of PhoneNumbers
  • Each PhoneNumber has a parent contact (this is the bidirectional many-to-one relationship)
What I am trying to do is to serialize a conversation.
If I don't use @JsonManagedReference and @JsonBackReference then jackson will crashe due to an infinite loop. But when I use them, the Contact doesn't get serialized into the PhoneNumber.
Class Contact {
  @JsonManagedReference
  List<PhoneNumber> phoneNumber ;
}
Class PhoneNumber {
  @JsonBackReference 
  Contact contact;
}
The output is :
{    <--------------------- Conversation
    "id": 51,
    "smsSet": [
      {
        "id": 53,
        "origin": 0123465,
        "destination": "06533844XY",
        "message": "Hello world!",
        "phoneNumbers": [
          {
            "id": 64,
            "num": "06533844XY",
            "creationDate": 1333992533000,
          }
        ],
      }
    ],
    "creationDate": 1333992534000
  }
instead of
{    <---------- conversation
    "id": 51,
    "smsSet": [
      {
        "id": 53,
        "origin": 0123465,
        "destination": "06533844XY",
        "message": "Hello world!",
        "phoneNumbers": [
          {
            "id": 64,
            "num": "06533844XY",
            "creationDate": 1333992533000,
            "contact":  <--------------------- Missing part
             {
                "id": 12,
                "name": "Samuel Jackson",
                "primaryNumber": "06533844XY"
             }
          }
        ],
      }
    ],
    "creationDate": 1333992534000
  }
credit : http://stackoverflow.com/questions/10097865/jackson-confused-with-bidirectional-one-to-many-relationship

โพสต์ยอดนิยมจากบล็อกนี้

J2EE คืออะไร

วิธีแก้ : แก้ไขตารางแล้ว save ไม่ได้ ต้องสร้างใหม่ - Saving changes is not permitted in SQL Server Management Studio

การออกแบบ RESTful API - วิธีปฏิบัติที่ดี