0

I'm trying to test vertx mapping between JsonObject and a pojo. I added methods fromJson and toJson which will be added to json-mappers.properties. for use in vertx. The class is immutable and using lombok @Value and @Builder.

@Value
@Jacksonized
@Builder
public class AdSystem {
    String version;
    String system;

    public Optional<String> getVersion() {
        return Optional.ofNullable(version);
    }

    public Optional<String> getSystem() {
        return Optional.ofNullable(system);
    }

    public JsonObject toJson() {
        return JsonObject.mapFrom(this);
    }

    public static AdSystem fromJson(JsonObject jsonObject) {
        return jsonObject.mapTo(AdSystem.class);
    }
}

When I test this deserialization works but serialization does not.

    @Test
    public void toJson_passes() {
        var system = new AdSystem("1", "iabtechlab");
        var json = system.toJson();
        assertThat(json).isEqualTo(new JsonObject().put("version", "1").put("system", "iabtechlab"));
    }

    @Test
    public void fromJson_passes() {
        var json = new JsonObject().put("version", "1").put("system", "iabtechlab");
        var system = AdSystem.fromJson(json);
        assertThat(system).isEqualTo(new AdSystem("1", "iabtechlab"));
    }

toJson fails and this is the result.

org.junit.ComparisonFailure: 
Expected :{"version":"1","system":"iabtechlab"}
Actual   :{"version":{"empty":false,"present":true},"system":{"empty":false,"present":true}}

What am I doing wrong?

John Mercier
  • 1,637
  • 3
  • 20
  • 44
  • Does this answer your question? [Using Jackson ObjectMapper with Java 8 Optional values](https://stackoverflow.com/questions/25693309/using-jackson-objectmapper-with-java-8-optional-values) – Arnaud Claudel Jul 20 '23 at 19:52
  • @ArnaudClaudel partially. This is the right direction but how do I get the jdk8 module to work with vertx JsonObject? – John Mercier Jul 21 '23 at 13:16

1 Answers1

0

Add support for Optional to the mapper used by vertx. This has to be done in the application and before running tests. As an example, it can be added to an @Before method in these tests.

    @Before
    public void setup() {
        DatabindCodec.mapper()
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule());
    }
John Mercier
  • 1,637
  • 3
  • 20
  • 44