dependencies:
compile("com.fasterxml.jackson.core:jackson-annotations") compile("com.fasterxml.jackson.core:jackson-core") compile("com.fasterxml.jackson.core:jackson-databind")
examples:
public class JacksonSerializerTest { @Test public void testJsonIgnoreProperties() throws IOException { ObjectMapper mapper = new ObjectMapper(); PersonDTO dto = new PersonDTO(); dto.setAge(18); dto.setName("Jack"); dto.setId(1); String jsonStr = mapper.writeValueAsString(dto); PersonDTO dto1 = mapper.readValue(jsonStr, PersonDTO.class); assertTrue(dto1.getName() == null); String jsonStr1 = "{\"id\":1, \"name\":\"Jack\"}"; PersonDTO dto2 = mapper.readValue(jsonStr1, PersonDTO.class); assertTrue(dto2.getName() == null); } @Test public void testJsonIgnore() throws IOException { ObjectMapper mapper = new ObjectMapper(); PersonDTO dto = new PersonDTO(); dto.setId(2); dto.setMale(true); String jsonStr = mapper.writeValueAsString(dto); PersonDTO dto1 = mapper.readValue(jsonStr, PersonDTO.class); assertTrue(dto1.getMale() == false); } @Test public void testCustomSerializer() throws IOException { ObjectMapper mapper = new ObjectMapper(); PersonDTO dto = new PersonDTO(); dto.setId(3); dto.setWeight(Double.valueOf(65.371)); String jsonStr = mapper.writeValueAsString(dto); PersonDTO dto1 = mapper.readValue(jsonStr, PersonDTO.class); assertTrue(dto1.getWeight().equals(Double.valueOf(65.4))); } @Test public void testJsonNaming() throws IOException { String nickName = "JK."; ObjectMapper mapper = new ObjectMapper(); PersonDTO dto = new PersonDTO(); dto.setId(4); dto.setNickName(nickName); String jsonStr = mapper.writeValueAsString(dto); PersonDTO dto1 = mapper.readValue(jsonStr, PersonDTO.class); assertTrue(dto1.getNickName().equals(nickName)); } @JsonIgnoreProperties(value = {"name", "age"}) @Data @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public static class PersonDTO { private int id; private String name; private int age; @JsonIgnore private boolean male; @JsonSerialize(using = CustomDoubleSerialize.class) private Double weight; private String nickName; public boolean getMale() { return this.male; } } public static class CustomDoubleSerialize extends JsonSerializer<Double> { private DecimalFormat df = new DecimalFormat("##.0"); @Override public void serialize(Double value, JsonGenerator jgen,SerializerProvider provider) throws IOException,JsonProcessingException { jgen.writeString(df.format(value)); } } }