Note that there are some explanatory texts on larger screens.

plurals
  1. POJackson/GSON: Selecting a different representation when object has been reached via a relationship
    primarykey
    data
    text
    <p>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.</p> <p>Example: So, say a Person has a Dog and a Dog has a Person.</p> <pre><code>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 } </code></pre> <p>When serialising a given dog, I need the result to be:</p> <pre><code>{"id": 24, "name": "Fifo", "owner": 42} </code></pre> <p>And when serialising a given Person, I need the result to be:</p> <pre><code>{"id": 42, "firstName": "John", "lastName": "Blogs", "dog": 24} </code></pre> <p>rather than</p> <pre><code>{"id": 24, "name": "Fifo", "owner": {"id": 42, "firstName": "John", "lastName": "Blogs", "dog": 24} } </code></pre> <p>and</p> <pre><code>{"id": 42, "firstName": "John", "lastName": "Blogs", "dog": {"id": 24, "name": "Fifo", "owner": 42} } </code></pre> <p>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.</p> <p>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.</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload