【问题标题】:In Json: What exactly is a "direct self-reference"在 Json 中:究竟什么是“直接自引用”
【发布时间】:2012-08-11 00:53:08
【问题描述】:

这个问题可能看起来很愚蠢,但对我来说,循环引用是例如对象 A 引用对象 B 并且对象 B 引用对象 A。

我正在使用一个 android 应用程序与带有 objectify DB 的 GAE 服务器通信。

我的模型很简单,但出现错误:

org.codehaus.jackson.map.JsonMappingException: Direct self-reference leading to cycle (through reference chain: java.util.ArrayList[0]->com.my.model.MyMessage["senderKey"]->com.googlecode.objectify.Key["root"])

这是我的模型:MyMessage 引用 MyUser(MyUser DOESNT 引用 MyMessage...

代码如下:

public class MyMessage implements Serializable {
private static final long serialVersionUID = -1075184303389185795L;

@Id
private Long id;

@Unindexed
private String sendMessage;

@Unindexed
private String answerMessage;

private MessageStatus status = MessageStatus.FREE;

@Parent
Key<MyUser> senderKey;

Key<MyUser> answererKey;

@SuppressWarnings("unused")
private MyMessage() {
}

public MyMessage(MyUser user, String message) {
    super();
    this.sendMessage = message;
    this.senderKey = new Key<MyUser>(MyUser.class, user.getId());
}

[... getters and setters ...]
}

.

public class MyUser implements Serializable {

private static final long serialVersionUID = 7390103290165670089L;
@Id private String id;

@SuppressWarnings("unused")
private MyUser() {
    this.setId("default");
}

public MyUser(String mail) {
    this.setId(mail);
}

public void setId(String mail) {
    this.id = mail;
}

public String getId() {
    return id;
}

}

那么,究竟什么是直接自引用??我的模型有什么问题??

谢谢。

【问题讨论】:

  • 再次查看Exception。它在抱怨Key,而不是MyUserKey.root 是什么?还请包括Key 的定义。
  • com.my.model.MyMessage["senderKey"]->com.googlecode.objectify.Key["root"])。看:Key.root 来自 com.googlecode.objectify.Key。这不是我的代码的一部分...

标签: java json google-app-engine restlet objectify


【解决方案1】:

Key 内部包含对父 Key 的引用,这是对 iteslf 的类型引用,即直接自引用。这可能会导致无限循环,因此 Jackson 会抛出错误。

底线:Key 不可序列化开箱即用。你可以写一个自定义的 Jackson serializer/deserializer

【讨论】:

  • “密钥内部包含对父密钥的引用”这是否意味着我无法将我的实体发送给客户端?有没有办法解决这个问题??
猜你喜欢
  • 2014-06-03
  • 2010-12-29
  • 2011-06-10
  • 2019-08-12
  • 2014-10-28
  • 2012-08-27
  • 2010-11-12
  • 2011-03-18
  • 2011-01-22
相关资源
最近更新 更多