Merge pull request #6051 from mchugunov/BAEL-2475-deserialize-immutable-objects

BAEL-2475: Deserialize immutable objects
This commit is contained in:
Eric Martin 2019-01-13 22:09:09 -06:00 committed by GitHub
commit 14771a3b2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,24 @@
package com.baeldung.jackson.deserialization.immutable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Employee {
private final long id;
private final String name;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Employee(@JsonProperty("id") long id, @JsonProperty("name") String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jackson.deserialization.immutable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
@JsonDeserialize(builder = Person.Builder.class)
public class Person {
private final String name;
private final Integer age;
private Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@JsonPOJOBuilder
static class Builder {
String name;
Integer age;
Builder withName(String name) {
this.name = name;
return this;
}
Builder withAge(Integer age) {
this.age = age;
return this;
}
Person build() {
return new Person(name, age);
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jackson.deserialization.immutable;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class ImmutableObjectDeserializationUnitTest {
@Test
public void whenPublicConstructorIsUsed_thenObjectIsDeserialized() throws IOException {
final String json = "{\"name\":\"Frank\",\"id\":5000}";
Employee employee = new ObjectMapper().readValue(json, Employee.class);
assertEquals("Frank", employee.getName());
assertEquals(5000, employee.getId());
}
@Test
public void whenBuilderIsUsedAndFieldIsNull_thenObjectIsDeserialized() throws IOException {
final String json = "{\"name\":\"Frank\"}";
Person person = new ObjectMapper().readValue(json, Person.class);
assertEquals("Frank", person.getName());
assertNull(person.getAge());
}
@Test
public void whenBuilderIsUsedAndAllFieldsPresent_thenObjectIsDeserialized() throws IOException {
final String json = "{\"name\":\"Frank\",\"age\":50}";
Person person = new ObjectMapper().readValue(json, Person.class);
assertEquals("Frank", person.getName());
assertEquals(50, (int) person.getAge());
}
}