I am trying to use @JsonView annotation for my nested entities. To be more clear, assume that, we have 2 entities, each entity have its own view class.
public class JsonViewAddress {
//some view classes
}
public class Address {
//fields annotated by JsonViewAddress's classes and @JsonProperty
}
public class JsonViewPerson {
//some view classes
}
public class Person {
//some fields (yes annotated with JsonViewPerson classes and @JsonProperty)
//also assume that this is annotated with any JsonViewPerson's class.
private Address address;
}
Let's try to achieve this Person class with Json type from response
@Path("hey")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Resource {
@GET
@Path("/stack/overflow")
@JsonView(value = { /* WHAT SHOULD BE WRITTEN HERE ? */ })
public Response method() {
//return Person entity in response
}
}
@JsonView annotation takes String array, but how should i determine that these written view classes must be work explicitly for each entity they belonged ? I want to see that UserView works for User, AddressView works for Address, shortly.
thanks.
I had a similar problem, it's not exactly your problem but maybe the approach will be usefull for you.
I only use one ViewObject
public class Views {
public static class Low {
}
public static class Medium extends Low {
}
public static class High extends Medium {
}
}
Every time that i have a nested object i need it in the Views.Low View, so i write a Serializer to do this.
public class Serializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writerWithView(Views.Low.class).writeValue(jgen, value);
}
}
Finally in my objects i used like this:
public class Person {
@JsonView(Views.High.class)
@JsonSerialize(using = Serializer.class)
private Address address;
}
The resource:
@Path("hey")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Resource {
@GET
@Path("/stack/overflow")
@JsonView(Views.High.class)
public Response method() {
//return Person entity in response with address low view
}
@GET
@Path("/stack/overflow")
@JsonView(Views.Medium.class)
public Response method() {
//return Person entity in response with no address
}
}
You can use this approach to your problem, but if you use different Class Views you have to write a lot of Serializers.
来源:https://stackoverflow.com/questions/19638550/how-does-jsonview-annotation-can-be-used-for-nested-entities