Daniele Licitra Daniele Licitra - 6 months ago 20
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")
@JsonIdentityReference(alwaysAsId=true)
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
}
}

Answer

Solved adding a Json Serializer.

I have created an NationJsonSerializer for the parent class:

public class NationJsonSerializer extends JsonSerializer<TNation> {

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

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.