Skip to content

Instantly share code, notes, and snippets.

@audacus
Last active October 11, 2016 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audacus/e70ce0f3cd4b17197d911769e05b237e to your computer and use it in GitHub Desktop.
Save audacus/e70ce0f3cd4b17197d911769e05b237e to your computer and use it in GitHub Desktop.
Example solution for stackoverflow question: http://stackoverflow.com/q/39986844/3442851
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CustomDeserializer {
public void doStuff() {
try {
String json = "{\"key1\":\"val1\",\"key2\":\"blank\"}";
// item
ObjectMapper mapperItem = new ObjectMapper();
SimpleModule moduleItem = new SimpleModule();
moduleItem.addDeserializer(Item.class, new ItemDeserializer());
mapperItem.registerModule(moduleItem);
Item item = mapperItem.readValue(json, Item.class);
// map
ObjectMapper mapperMap = new ObjectMapper();
SimpleModule moduleMap = new SimpleModule();
moduleMap.addDeserializer(Map.class, new MapDeserializer());
mapperMap.registerModule(moduleMap);
Map map = mapperMap.readValue(json, Map.class);
} catch (Exception e) {
e.printStackTrace();
}
}
class Item {
String key1;
String key2;
Item(String key1, String key2) {
this.key1 = key1;
this.key2 = key2;
}
}
public class ItemDeserializer extends StdDeserializer<Item> {
public ItemDeserializer() {
this(null);
}
public ItemDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Item deserialize(JsonParser jp, DeserializationContext context)
throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
String key1 = node.get("key1").asText();
String key2 = node.get("key2").asText();
if (key1.equals("blank")) {
key1 = null;
}
if (key2.equals("blank")) {
key2 = null;
}
return new Item(key1, key2);
}
}
public class MapDeserializer extends StdDeserializer<Map<String, String>> {
public MapDeserializer() {
this(null);
}
public MapDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Map<String, String> deserialize(JsonParser jp, DeserializationContext context)
throws IOException {
// definitely not the best way but it works...
Map<String, String> map = new HashMap<>();
String[] keys = new String[] {"key1", "key2"};
JsonNode node = jp.getCodec().readTree(jp);
String value;
for (String key : keys) {
value = node.get(key).asText();
if (value.equals("blank")) {
value = null;
}
map.put(key, value);
}
return map;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment