I'm currently playing around with Jackson's de/serialization features and I encountered a problem, I don't know how to solve.
During my test the @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
annotation is ignored and it only shows null
.
However with e.g. Postman everything works as expected.
I using just a Spring Boot Starter with Web Starter and Test Starter dependency.
Example Code:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class JacksonExampleRestController {
@PostMapping("/api")
public void getResti(@RequestBody JacksonModel jacksonModel) {
System.out.println(jacksonModel.getId());
System.out.println(jacksonModel.getPassword());
}
}
class JacksonModel {
private String id;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Test:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {
private MockMvc mockMvc;
@Before
public void setUp() {
JacksonExampleRestController jacksonExampleRestController = new JacksonExampleRestController();
mockMvc = MockMvcBuilders.standaloneSetup(jacksonExampleRestController)
.build();
}
@Test
public void testJackson() throws Exception {
JacksonModel jacksonModel = new JacksonModel();
jacksonModel.setId("id");
jacksonModel.setPassword("password");
mockMvc.perform(post("/api").
contentType(APPLICATION_JSON_UTF8)
.content(convertObjectToJsonBytes(jacksonModel)));
}
public static byte[] convertObjectToJsonBytes(Object object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
}
}
Is this the default behaviour and do I have to configure something in my test or is it something else I don't see right now?