Spring @ResponseBody Json Cyclic Reference

时间:2012-03-15 20:02:31

标签: java spring spring-mvc jackson bidirectional-relation

我正在尝试使用Spring 3.x @ResponseBody生成json / xml响应,当有很多关系b / w表时我使用JPA 2.0 ORM然后json抛出LazyInitializationException

如果我提供“渴望获取”,那么它将进入循环引用。

3 个答案:

答案 0 :(得分:3)

根据您的评论判断,只需创建自定义Serializer

您的JsonSerializer。您可以为要尝试序列化的每种对象类型使用这些。

public class MyObjectJsonSerializer extends JsonSerializer<MyObject> {

@Override
public Class<MyObject> handledType() {
    return MyObject.class;
}

@Override
public void serialize(MyObject myObject, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeNumberField("id", myObject.getId());
    // whatever else you need
    jgen.writeEndObject();
}

}

您的ObjectMapper

public class MyObjectMapper extends ObjectMapper {

public MyObjectMapper() {
    SimpleModule module = new SimpleModule("My Module", new Version(1, 0, 0, "SNAPSHOT"));
    module.addSerializer(new MyObjectJsonSerializer());

    this.registerModule(module);
}

}

然后在你的spring-config.xml中。

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="myObjectMapper" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="myObjectMapper" class="com.manne.app.objectmapper.MyObjectMapper" />

答案 1 :(得分:3)

我最近遇到了类似的问题:Jackson - serialization of entities with birectional relationships (avoiding cycles)

因此,解决方案是升级到Jackson 2.0,并向类中添加以下注释:

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

然后问题是Spring不能与Jackson 2.0一起工作。这已通过以下方式解决:

<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>

own.implementation.of.MappingJacksonHttpMessageConverter基于此:

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

但是使用ObjectMapper和Jackson 2.0中的其他Jackson类而不是Jackson 1。*

答案 2 :(得分:1)

听起来您正在将ORM管理的对象序列化为JSON,但尚未初始化所有子关联,导致LazyInitializationException,因为您的Controller没有数据库连接的句柄。 2个选择:

  1. 初始化DAO层中的所有对象的子关联
  2. 将ORM管理的对象转换为TO并将其传递给Controller以转换为JSON