JsonMappingException: How to transfert a Objectify Entity (with Key) through Restlet

橙三吉。 提交于 2019-12-11 11:37:31

问题


I am developping an Android Application, comunicating with a GAE server + Objectify DB.

I choose Restlet for rest framework.

I have a problem when I try to retrieve an Entity with a Key attribute. The server throws an error:

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"])

Here is my model (very simple):

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

@Id
private Long id;

@Unindexed
private String sendMessage;

@Parent
Key<MyUser> senderKey;

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;

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

public MyUser(String mail) {
    this.setId(mail);
}
[... getters and setters ...]

}

What can I do to solve this problem??


回答1:


Objectify's Key has a convenience method getRoot() that returns the root element in the ancestor chain. When a key is the root, getRoot() returns this. Jackson detects this as a cycle and thus you get the error.

The best way to deal with this is not to try to serialize Keys as json objects. Keys are much better represented in JSON as the stringified version.

I don't know how you do this in Restlet, but you need to modify the ObjectMapper instance to provide a KeySerializer that does this translation. Look at the ObjectifyJacksonModule in Objectify4 for guidance:

https://code.google.com/p/objectify-appengine/source/browse/src/com/googlecode/objectify/util/jackson/ObjectifyJacksonModule.java




回答2:


Did you include

<inherits name="com.googlecode.objectify.Objectify" />

in your GWT module ?




回答3:


I had a similar problem that resulted in this exact error. Having reduced the code to its absolute essentials I have discovered that I will see this error if I return a Key object from an AppEngine API Method.

i.e.

@ApiMethod(name = "insertPureContainer", path="insertPureContainer", httpMethod = ApiMethod.HttpMethod.POST)
public Key insertPureContainer(PureContainer container, User user) throws OAuthRequestException {

    return ofy().save().entity(container).now();    

}

WILL result in this error, returning the updated object does not.



来源:https://stackoverflow.com/questions/11968513/jsonmappingexception-how-to-transfert-a-objectify-entity-with-key-through-res

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!