Created
June 6, 2016 21:39
-
-
Save iambic69/b58136a9f513a2fd9459c8753e15d785 to your computer and use it in GitHub Desktop.
Demonstrate serialization and deserialization of lowercase enums using Jackson 2.6 onwards.
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 com.fasterxml.jackson.annotation.JsonProperty; | |
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.databind.SerializationFeature; | |
import java.io.IOException; | |
/** | |
* Demonstrate serialization and deserialization | |
* of lowercase enums using Jackson 2.6 onwards. | |
* | |
* @author Andrew Bickerton | |
*/ | |
public class LowercaseEnumsWithJackson { | |
public static class Endpoint { | |
public enum DataType { | |
@JsonProperty("json") | |
JSON, | |
@JsonProperty("html") | |
HTML | |
} | |
public String url; | |
public DataType type; | |
public Endpoint() { | |
} | |
@Override | |
public String toString() { | |
final StringBuilder sb = new StringBuilder("Endpoint{"); | |
sb.append("url='").append(url).append('\''); | |
sb.append(", type=").append(type); | |
sb.append('}'); | |
return sb.toString(); | |
} | |
} | |
private static ObjectMapper mapper = new ObjectMapper() {{ | |
configure(SerializationFeature.INDENT_OUTPUT, true); | |
}}; | |
public static void main(String[] args) throws IOException { | |
deserialize(); | |
serialize(); | |
} | |
private static void deserialize() throws IOException { | |
final String input = "{\"url\":\"foo\",\"type\":\"json\"}"; | |
final Endpoint endpoint = mapper.readValue(input, Endpoint.class); | |
System.out.println("endpoint = " + endpoint); | |
} | |
private static void serialize() throws JsonProcessingException { | |
final Endpoint endpoint = new Endpoint(){{ | |
url = "foo"; | |
type = DataType.JSON; | |
}}; | |
final String output = mapper.writeValueAsString(endpoint); | |
System.out.println("output = " + output); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment