Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Deserialize json for class having Optional fields using Jackson

I'm using Jackson to deserialise a class which has Optional member variables, so it looks like

class Test{
   Optional<String> testString;
}

but in serialised form it looks like, which is legit

{
"value": {
"testString": "hi"
}

How can I deserialise it back to my Test class?, because when I try to do so it says unknown field "value". Can it be possible without changing my test class.

like image 478
Siddharth Thakrey Avatar asked Sep 05 '25 03:09

Siddharth Thakrey


1 Answers

You need to register Jdk8Module. Belowe you can find example, how to do that:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;

import java.io.File;
import java.util.Optional;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new Jdk8Module());

        Test test = new Test();
        test.setTestString(Optional.of("str"));

        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(test);
        System.out.println(json);
        System.out.println(mapper.readValue(json, Test.class));
    }
}

Above code prints:

{
  "testString" : "str"
}
Test{testString=Optional[str]}

See also:

  1. jackson-modules-java8
like image 78
Michał Ziober Avatar answered Sep 08 '25 00:09

Michał Ziober