Daniele Licitra Daniele Licitra - 11 months ago 49
Java Question

JAVA JACKSON: serialize a class with two field instead of all class

I need to serialize an entity with only two column when it's called by a foreign key. I'am working in Wildfly, so I'am searching for a jackson solutions.

Suppose I have entity class A

public class A{
private Long id;
private String name;
private String anotherinfo;
private String foo;

and another class B:

public class B{
private Long id;
private String name;
private A parent;

I want to serialize A with all his field when i search for A, but when i need to retrieve an istance of B, i need only two field (an ID and a label)

If I use annotations:

@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
private A parent;

i'll return only the id.

The result i want will be like:

B: {
"id" : 1,
"name" : "test",
"parent" : {
"id" : 1,
"name" : 2


Solved adding a Json Serializer.

I have created an NationJsonSerializer for the parent class:

public class NationJsonSerializer extends JsonSerializer<TNation> {

public void serialize(TNation value, JsonGenerator jgen, SerializerProvider provider) 
  throws IOException, JsonProcessingException {
    jgen.writeNumberField("id", value.getId());
    jgen.writeStringField("name", value.getComune());
    jgen.writeStringField("iso", value.getCap());

Then,in the city class, i put the annotation

@JoinColumn(name = "idtnation",referencedColumnName = "id",nullable = true)
@ManyToOne(targetEntity = TNation.class, fetch = FetchType.EAGER)
@JsonSerialize(using = NationJsonSerializer.class)
private TNation nation;

So, if I use a method Nation n = getNation(long id); i'll receive all columns, but if i use getCity(), I'll receive a simplified version.