Add Adapter Sample

This commit is contained in:
Juan M.vi 2017-11-22 00:49:35 -03:00
parent 511c32f3b0
commit d20693e31b
3 changed files with 57 additions and 1 deletions

View File

@ -0,0 +1,26 @@
package com.baeldung.adapter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.bind.adapter.JsonbAdapter;
import com.baeldung.jsonb.Person;
public class PersonAdapter implements JsonbAdapter<Person, JsonObject> {
@Override
public JsonObject adaptToJson(Person p) throws Exception {
return Json.createObjectBuilder()
.add("id", p.getId())
.add("name", p.getName())
.build();
}
@Override
public Person adaptFromJson(JsonObject adapted) throws Exception {
Person person = new Person();
person.setId(adapted.getInt("id"));
person.setName(adapted.getString("name"));
return person;
}
}

View File

@ -22,10 +22,10 @@ public class Person {
private BigDecimal salary;
public Person() {
this(0, "", "", 0, LocalDate.now(), new BigDecimal(0));
}
public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
super();
this.id = id;
this.name = name;
this.email = email;

View File

@ -17,6 +17,8 @@ import javax.json.bind.config.PropertyOrderStrategy;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import com.baeldung.adapter.PersonAdapter;
public class JsonbTest {
@Test
@ -155,4 +157,32 @@ public class JsonbTest {
.equals(person));
}
@Test
public void givenPersonObject_whenSerializeWithAdapter_thenGetPersonJson() {
JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon");
String jsonPerson = jsonb.toJson(person);
// @formatter:off
String jsonExpected =
"{\"id\":1," +
"\"name\":\"Jhon\"}";
// @formatter:on
assertTrue(jsonExpected.equals(jsonPerson));
}
@Test
public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() {
JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon");
// @formatter:off
String jsonPerson =
"{\"id\":1," +
"\"name\":\"Jhon\"}";
// @formatter:on
assertTrue(jsonb.fromJson(jsonPerson, Person.class)
.equals(person));
}
}