Jackson confused with bidirectional one-to-many relationship

前端 未结 4 2102
天命终不由人
天命终不由人 2020-12-14 22:53

I\'m using jackson 1.9.2 with Hibernate/Spring MVC through MappingJacksonHttpMessageConverter.

Jackson can not serialize bidirectional one-to-many relationship and

相关标签:
4条回答
  • 2020-12-14 23:11

    You can add @JsonIgnore to fields and the mapper will skip over them during serialization. It is similar in function to @Transient.

    It is in the jackson-core-asl.

    0 讨论(0)
  • 2020-12-14 23:14

    I recently encountered a similar problem: Jackson - serialization of entities with birectional relationships (avoiding cycles)

    So the solution is to upgrade to Jackson 2.0, and add to classes the following annotation:

    @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, 
                      property = "@id")
    public class SomeEntityClass ...
    

    Then the problem is that Spring doesn't work with Jackson 2.0. This has been solved in the following way:

    <bean id="jacksonMessageConverter"
              class="own.implementation.of.MappingJacksonHttpMessageConverter"/>
    
    <bean class="org.springframework.web.servlet.mvc
                 .annotation.AnnotationMethodHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <ref bean="jacksonMessageConverter"/>
                </list>
            </property>
            <property name="requireSession" value="false"/>
        </bean>
    

    And the own.implementation.of.MappingJacksonHttpMessageConverter is based on this:

    http://www.jarvana.com/jarvana/view/org/springframework/spring-web/3.0.0.RELEASE/spring-web-3.0.0.RELEASE-sources.jar!/org/springframework/http/converter/json/MappingJacksonHttpMessageConverter.java?format=ok

    But use ObjectMapper and other Jackson classes from Jackson 2.0 instead of Jackson 1.*

    0 讨论(0)
  • 2020-12-14 23:27

    One thing wrong in your class def is use of untyped List; you should rather have:

    List<PhoneNumber> phoneNumber ;
    

    since otherwise Jackson can not know what the type is when deserializing; and even on serializing it could cause problems (as base type is not known for sure). So I would first fix this issue.

    But additionally your dependency may be wrong way around: @JsonManagedReference MUST always be the first thing to serialize. If this is not the case, you can not use these annotations. Without seeing objects you are trying to serialize it is hard to know for sure (POJO definition and JSON seem slightly off).

    0 讨论(0)
  • 2020-12-14 23:28

    As a first solution, I kept these annotations and created an other class: ContactWithouPhoneNumber and added it as a field to the PhoneNumber class.

    Now, before rendering, I copy all fields except PhoneNumber, from contact to contactWithoutPhoneNumber. The output JSON contains every thing I need.

    This is the DTO design pattern.

    0 讨论(0)
提交回复
热议问题