Last active
December 18, 2015 06:08
-
-
Save blinsay/5737355 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Soooo, I have a POJO with an Optional<T> field that *isn't set by default*. When the field isn't included in | |
a JSON document, I'd like that field to be deserialized as Optional.absent() rather than 'null'. Just doing | |
the default thing (below) I end up having the Optional<T> field being set to null after deserialization. | |
I suspect that Jackson is being smart and just not setting fields that aren't in the JSON. Is there something | |
I can do to make sure it initalizes all the fields, or is the Right Thing To Do just to give my Optional<T> | |
field a default value? | |
*/ | |
public class AbsentTest { | |
public static class Nothing { | |
public Nothing() {/*jackson*/} | |
private Optional<Set<String>> optionalSet; | |
public Optional<Set<String>> getOptionalSet() { | |
return optionalSet; | |
} | |
@Override | |
public String toString() { | |
return "Nothing{" + | |
"optionalSet=" + optionalSet + | |
'}'; | |
} | |
} | |
/** | |
* Outputs "Nothing{optionalSet=null}" | |
*/ | |
@Test | |
public void testWithNoValues() throws IOException { | |
final ObjectMapper mapper = new ObjectMapper(); | |
mapper.registerModule(new GuavaModule()); | |
System.err.println(mapper.readValue("{}", Nothing.class)); | |
} | |
/** | |
* Outputs "Nothing{optionalSet=Optional.of([3, 2, 1])}" | |
*/ | |
@Test | |
public void testWithSomeValues() throws IOException { | |
final ObjectMapper mapper = new ObjectMapper(); | |
mapper.registerModule(new GuavaModule()); | |
System.err.println(mapper.readValue("{\"optionalSet\": [\"1\", \"2\", \"3\"]}", Nothing.class)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment