Permalink
Browse files

arrays of objects! :)

  • Loading branch information...
1 parent f88f150 commit bb333ec9e124ad193c6ed4a1e86336f93721aed8 Robey Pointer committed Aug 23, 2010
View
10 src/main/scala/com/twitter/streamyj/StreamyUnpacker.scala
@@ -31,6 +31,8 @@ class StreamyUnpacker {
coerceBoolean(name, cls, obj.asInstanceOf[Boolean])
} else if (objcls == classOf[List[AnyRef]] || objcls == classOf[::[AnyRef]]) {
coerceList(name, cls, obj.asInstanceOf[List[AnyRef]])
+ } else if (cls isAssignableFrom objcls) {
+ obj.asInstanceOf[B]
} else {
throw new JsonUnpackingException("Don't know how to coerce " + objcls)
}
@@ -174,10 +176,14 @@ class StreamyUnpacker {
case ValueNull => list += null
case StartArray =>
if (!cls.isArray) {
- throw new JsonUnpackingException("Can't unpack nested lists due to type erasure")
+ throw new JsonUnpackingException("Can't unpack nested lists due to type erasure (try arrays)")
}
list += getArray(streamy, cls.getComponentType)
-// case object StartObject extends StreamyToken
+ case StartObject =>
+ if (!cls.isArray) {
+ throw new JsonUnpackingException("Can't unpack lists of objects due to type erasure (try arrays)")
+ }
+ list += unpackObject(streamy, cls.getComponentType)
case x =>
throw new JsonUnpackingException("Unexpected token: " + x)
}
View
13 src/test/scala/com/twitter/streamyj/StreamyUnpackerSpec.scala
@@ -129,5 +129,18 @@ object StreamyUnpackerSpec extends Specification {
case class ListStar(name: String, position: List[List[Int]])
StreamyUnpacker[ListStar](data) must throwA[Exception]
}
+
+ "array of objects" in {
+ val data = """{"name":"Santa","roster":[{"name":"Robey","good":true},{"name":"Rus","good":true}]}"""
+
+ case class Recipient(name: String, good: Boolean)
+ case class ArrayGifter(name: String, roster: Array[Recipient])
+ val arraySanta = StreamyUnpacker[ArrayGifter](data)
+ arraySanta.name mustEqual "Santa"
+ arraySanta.roster.toList mustEqual List(Recipient("Robey", true), Recipient("Rus", true))
+
+ case class ListGifter(name: String, roster: List[Recipient])
+ StreamyUnpacker[ListGifter](data) must throwA[Exception]
+ }
}
}

0 comments on commit bb333ec

Please sign in to comment.