I have a Spring API that allows the user to specify the JsonView of each call using a view param like so:
/api/v1/person/1?view=viewName
I then use Spring's MappingJacksonValue to set the correct view dynamically instead of using @JsonView()
annotation and finally I just return the MappingJacksonValue instance which produces something along the lines of
[
{ id: 1 },
{ id: 2 }
]
I can't for the life of me figure out how to easily wrap my MappingJacksonValue instances in an ObjectNode so that I can change all API results from the snippet above to this
{
"data" : [
{ id: 1 },
{ id: 2 }
]
}
I tried using a regular HashMap<> but that didn't work - the serialization completely ignores the MappingJacksonValue view and it also produces Map-specific results
{
data: {
value: [],
serializationView: "com.blah.models.view.View$Id",
filters: null,
jsonpFunction: null
}
}
So can someone pls let me know what's the best way to achieve result wrapping in my scenario?
Thanks in advance!
If anyone comes across this post looking to do the same thing, I realized I was looking at the problem in the wrong way. I ended up creating a ServiceResponse class and wrapped up the object in there like so
public class ServiceResponse {
@JsonView(View.Id.class)
private Object data;
public ServiceResponse (Object data) {
this.data = data;
}
}
So essentially instead of returning new MappingJacksonValue(someReturnObject)
I'm returning new MappingJacksonValue(new ServiceResponse(someReturnObject))
. This way everything is wrapped nicely in a data
JSON object and the setSerializationView
method still filters my objects properly.
Hope this helps someone.