I have an API I can call to get some Json objects. Let's say I have two kind of objects : A
and B
.
an A
objects have a B
object amongst its instance variables. When I call my API to get someB
, I want the following result :
{
id: 234,
name: theBName,
colour: theBColour,
size: 123
}
but when I call my API to get someA
, I want the following result :
{
id: 456,
type: someAType,
b: {
id: 234,
name: theBName
}
}
As you can see, my B
object only have parts of its properties in the second case.
I have found how to serialize some proporties and not others using jsonViews
. I also know how to serialize an object as only its id
when serialized as part of another object by adding :
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public B someB;
to my A
object.
But for the life of me, i can't figure out how to serialize this B
object as its id
AND other properties of my choice when, and only when, it is serialized as part of an A
object.
I am looking for something like an annotation like this :
@serialiazeUsingOnlyProperties({"property1", "property2"})
public B someB;
to put in my A object.
You can use @JsonIgnoreProperties
. The annotation is commonly used at the class level but it applies to fields as well. when applied to a field, it is used to ignore properties inside the annotated field:
@JsonIgnoreProperties({"colour", "size"})
public B someB;