Created
July 6, 2012 13:53
-
-
Save worthlesscog/3060273 to your computer and use it in GitHub Desktop.
Polymorphic JSON unmarshall with Jackson in Scala
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 org.codehaus.jackson.annotate.{ JsonTypeInfo, JsonSubTypes, JsonProperty } | |
import org.codehaus.jackson.annotate.JsonSubTypes.Type | |
import org.codehaus.jackson.map.ObjectMapper | |
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") | |
@JsonSubTypes(Array( | |
new Type(value = classOf[Bingo], name = "x"), | |
new Type(value = classOf[Bongo], name = "y"), | |
new Type(value = classOf[Bungo], name = "z") | |
)) | |
abstract class Base | |
class Bingo(@JsonProperty("v") value: Int) extends Base | |
class Bongo(@JsonProperty("wigs") val wiggles: String, @JsonProperty("fish") val fish: Boolean) extends Base | |
class Bungo(@JsonProperty("soufflé") val soufflé: String) extends Base | |
object App { | |
def main(args: Array[String]) { | |
val bingo = """{"type":"x","v":"56"}""" | |
val bongo = """{"type":"y","wigs":"free wigs for everyone!","fish":"true"}""" | |
val bungo = """{"type":"z","soufflé":"no thanks, i've just put one out"}""" | |
new ObjectMapper().readValue(bongo, classOf[Base]) match { | |
case a: Bingo ⇒ println("Bingo!") | |
case b: Bongo ⇒ if (b.fish) println(b.wiggles) | |
case c: Bungo ⇒ println(c.soufflé) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment