Created
September 26, 2016 19:49
-
-
Save m-x-k/16b450ffa178d75b8fad6cd94eaac364 to your computer and use it in GitHub Desktop.
Jackson JsonView example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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