Last active
August 7, 2018 11:09
-
-
Save wicksome/49d4040ba296b7c24cb2b65f154a5de8 to your computer and use it in GitHub Desktop.
lombok(Value, Builder) + jackson
This file contains hidden or 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
@Value | |
@Builder | |
class ValueTest1 { | |
private String data1; | |
private Integer data2; | |
private int data3; | |
@JsonCreator | |
private ValueTest1(@JsonProperty("data1") String data1, @JsonProperty("data2") Integer data2, @JsonProperty("data3") int data3) { | |
this.data1 = data1; | |
this.data2 = data2; | |
this.data3 = 1; | |
} | |
} | |
@Value | |
@Builder | |
@AllArgsConstructor(access = AccessLevel.PRIVATE) | |
class ValueTest2 { | |
private String data1; | |
private Integer data2; | |
private int data3; | |
@JsonCreator | |
private ValueTest2(@JsonProperty("data1") String data1, @JsonProperty("data2") Integer data2) { | |
this.data1 = data1; | |
this.data2 = data2; | |
this.data3 = 1; | |
} | |
} | |
@Value | |
@Builder | |
@JsonDeserialize(builder = ValueTest3.ValueTest3Builder.class) | |
class ValueTest3 { | |
private String data1; | |
private Integer data2; | |
private int data3; | |
@JsonPOJOBuilder(withPrefix = "") // for json deserialize using jackson | |
static final class ValueTest3Builder { | |
} | |
} | |
public class JacksonWithValueAndBuilderOfLombokTest { | |
@Test | |
public void valueAnnotationJsonTest() throws IOException { | |
// given | |
final Class[] clzs = new Class[] {ValueTest1.class, ValueTest2.class, ValueTest3.class}; | |
final ObjectMapper objectMapper = new ObjectMapper(); | |
final String json = "{" | |
+ "\"data1\": \"test\"," | |
+ "\"data2\": 1," | |
+ "\"data3\": 1" | |
+ "}"; | |
for (Class clz : clzs) { | |
// when | |
final Object t = objectMapper.readValue(json, clz); | |
// then | |
System.out.println(t); | |
assertEquals("test", ReflectionTestUtils.getField(t, "data1")); | |
assertEquals(Integer.valueOf(1), ReflectionTestUtils.getField(t, "data2")); | |
assertEquals(1, ReflectionTestUtils.getField(t, "data3")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment