I have a large object graph from which I would like to expose objects in a RESTful via a web-service. All objects feature an id-property, which serves as a primary key unique within the objects of that class. Further, all relationships in my object graph are bi-directional. When exposing an instance as a REST resource, I need all attributes of the instance to be written to JSON; however, I want the instances that are associated via relationships merely to be represented by their id, rather than having the entire object serialised to JSON.
Example: So, say a Person has a Dog and a Dog has a Person.
class Person {
private Integer id;
private String firstName;
private String lastName;
private Dog dog;
// public getters/setters omitted
}
class Dog {
private Integer id;
private String name;
private Person owner;
// public getters/setters omitted
}
When serialising a given dog, I need the result to be:
{"id": 24, "name": "Fifo", "owner": 42}
And when serialising a given Person, I need the result to be:
{"id": 42, "firstName": "John", "lastName": "Blogs", "dog": 24}
rather than
{"id": 24, "name": "Fifo", "owner":
{"id": 42, "firstName": "John", "lastName": "Blogs", "dog": 24}
}
and
{"id": 42, "firstName": "John", "lastName": "Blogs", "dog":
{"id": 24, "name": "Fifo", "owner": 42}
}
respectively. I have played with the @JsonValue annotation in Jackson on the getId() method, but unfortunately, that applies always no matter whether the object it directly serialised or whether the object is reached via a relationship from another object.
I would have thought, that this use case is reasonably common. If this is not possible, what do other people do when exposing objects in an object graph via a RESTful API.
Thank you.
I can’t think of an obvious ways to do this with Jackson (there are many ways to override functionality, so there may be a way to do it with custom handlers, but that’s not simple), but it sounds like a good feature to bring on user/dev lists; others may well have implemented solutions, and it would be great to figure out a declarative solution here.
In fact I suspect that an annotation like @JsonKey could be added to handle simple cases where single property is used as the key. So a feature request might make sense.