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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With