Skip to content

Instantly share code, notes, and snippets.

@pluone
Last active May 4, 2017 15:25
Show Gist options
  • Save pluone/a5880266d638ecd0472a21339899aa83 to your computer and use it in GitHub Desktop.
Save pluone/a5880266d638ecd0472a21339899aa83 to your computer and use it in GitHub Desktop.
Json Enum serialization deserializtion
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
enum HelloEnum {
HELLO("h"),
WORLD("w");
private String shortName;
HelloEnum (String shortName) {
this.shortName = shortName;
}
@Override
public String toString() {
return shortName;
}
@JsonCreator
public static HelloEnum create (String value) {
if(value == null) {
throw new IllegalArgumentException();
}
for(HelloEnum v : values()) {
if(value.equals(v.getShortName())) {
return v;
}
}
throw new IllegalArgumentException();
}
public String getShortName() {
return shortName;
}
}
public class ExampleHelloEnum {
public static void main(String args[]) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Map<HelloEnum,String> testMap = new HashMap<HelloEnum,String>();
testMap.put(HelloEnum.HELLO, "hello string");
testMap.put(HelloEnum.WORLD, "world string");
System.out.println(objectMapper.writeValueAsString(testMap));
Map<HelloEnum,String> newTestMap = objectMapper.readValue(objectMapper.writeValueAsString(testMap), new TypeReference<Map<HelloEnum,String>>() {});
System.out.println(newTestMap.get(HelloEnum.HELLO));
System.out.println(newTestMap.get(HelloEnum.WORLD));
}
}
@pluone
Copy link
Author

pluone commented May 4, 2017

And here is the output:

{"h":"hello string","w":"world string"}
hello string
world string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment