Last active
May 4, 2017 15:25
-
-
Save pluone/a5880266d638ecd0472a21339899aa83 to your computer and use it in GitHub Desktop.
Json Enum serialization deserializtion
This file contains 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
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And here is the output:
{"h":"hello string","w":"world string"}
hello string
world string