Skip to content

Instantly share code, notes, and snippets.

@m-x-k
Created September 26, 2016 19:49
Show Gist options
  • Save m-x-k/16b450ffa178d75b8fad6cd94eaac364 to your computer and use it in GitHub Desktop.
Save m-x-k/16b450ffa178d75b8fad6cd94eaac364 to your computer and use it in GitHub Desktop.
Jackson JsonView example
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;
class Views {
public static class Normal{}
public static class WithTitle extends Normal{}
}
class Staff {
@JsonView(Views.WithTitle.class)
private String name;
@JsonView(Views.Normal.class)
private String title;
public Staff(String name, String title) {
this.name = name;
this.title = title;
}
public String getName() {
return name;
}
public String getTitle() {
return title;
}
}
class JacksonJsonViewExample {
public static void main(String[] args) throws Exception {
Staff staff = new Staff("Joe Bloggs", "Mr");
ObjectMapper mapper = new ObjectMapper();
// {"title":"Mr"}
System.out.println(mapper.writerWithView(Views.Normal.class).writeValueAsString(staff));
// {"name":"Joe Bloggs","title":"Mr"}
System.out.println(mapper.writerWithView(Views.WithTitle.class).writeValueAsString(staff));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment