/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lab.jefrajames.jsonb; import java.util.Objects; import java.util.OptionalInt; import java.util.logging.Level; import java.util.logging.Logger; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import org.junit.AfterClass; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; /** * * @author jefrajames */ public class OptionalIntTest { private static final Logger LOG = Logger.getLogger(OptionalIntTest.class.getName()); private static Jsonb jsonb; @BeforeClass public static void beforeClass() { jsonb = JsonbBuilder.create(); } @AfterClass public static void afterClass() throws Exception { if (jsonb != null) { jsonb.close(); } } @Test public void testWithAge() { Person initialData = new Person("Smith", OptionalInt.of(30)); LOG.log(Level.INFO, "testWithAge => initialData={0}", initialData); String jsonData = jsonb.toJson(initialData, Person.class); LOG.log(Level.INFO, "testWithAge => jsonData={0}", jsonData); Person fromJson = jsonb.fromJson(jsonData, Person.class); LOG.log(Level.INFO, "testWithAge => fromJson={0}", fromJson); assertEquals(initialData, fromJson); } @Test public void testWithouthAge() { Person initialData = new Person("Jack", OptionalInt.empty()); LOG.log(Level.INFO, "testWithouthAge => initialData={0}", initialData); String jsonData = jsonb.toJson(initialData, Person.class); LOG.log(Level.INFO, "testWithouthAge => jsonData={0}", jsonData); Person fromJson = jsonb.fromJson(jsonData, Person.class); LOG.log(Level.INFO, "testWithouthAge => fromJson={0}", fromJson); // Doesn't work assertEquals(initialData, fromJson); } public static class Person { private static final Logger LOG = Logger.getLogger(Person.class.getName()); private String name; private OptionalInt age; public Person() { } public Person(String name, OptionalInt age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public OptionalInt getAge() { return age; } public void setAge(OptionalInt age) { LOG.log(Level.INFO, "Person => calling setAge with parameter {0}", age); this.age = age; } @Override public String toString() { return "Person{" + "name=" + name + ", age=" + age + '}'; } @Override public int hashCode() { int hash = 5; hash = 67 * hash + Objects.hashCode(this.name); hash = 67 * hash + Objects.hashCode(this.age); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Person other = (Person) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.age, other.age)) { return false; } return true; } } }