MilacH MilacH - 2 months ago 7
Java Question

How display in json only one attribute of an entity in a oneToMany with itself?

I have a class embedded herself with a oneToMany relationship:

@Entity
public class A {

private String id;

@OneToMany(fetch = FetchType.EAGER)
private List<A> parents;
}


Thanks to the fetch, I can display easily the complete json of each parents.

But to avoid over data and loop, I would display only id of the item from "parents".

Any clues ?
Thank you.

EDIT:

After answer of marians27, I think about the reverse problem, for PUT and POST.
But how to do it for PUT/POST ?

By example, knowing that the object "embeded_id" is already in my database, I wanna pass to my API a json like :

{"A":
{
"id":"new_object_id",
"parents":
[{
"id":"embeded_id"
}]
}
}


instead of :

{"object":
{
"id":"new_object_id",
"parents":
[{
"id":"embeded_id",
"parents":[{...}]
}]
}
}


Here is the solution I found from here:

@Service
public class DeserializeA extends StdDeserializer<A> {

@Autowired
private IManager manager;

public DeserializeA() {
super(A.class);
}

public DeserializeA(Class<A> t) {
super(t);
}

@Override
public A deserialize(JsonParser jp, DeserializationContext arg1)
throws IOException, JsonProcessingException {
String id = null;
JsonToken currentToken = null;
while ((currentToken = jp.nextValue()) != null) {
switch (currentToken) {
case VALUE_STRING:
switch (jp.getCurrentName()) {
case "id":
id = jp.getText();
break;
default:
break;
}
break;
default:
break;
}
}

return manager.getAById(id);
}
}

Answer

You can use custom serializer. First annotate field, so that it uses your custom serializer:

@OneToMany(fetch = FetchType.EAGER)
@JsonSerialize(contentUsing = ParentSerializer.class)
private List<A> parents;

Then implement the serializer itself:

public class ParentSerializer extends StdSerializer<A> {
    public ParentSerializer() {
        super(A.class);
    }
    @Override
    public void serialize(A value, JsonGenerator gen, SerializerProvider  provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("id", value.getId());
        gen.writeEndObject();
    }
}
Comments