使用酸洗将一组json对象解析为scala对象

时间:2013-07-04 21:23:43

标签: java json scala scala-pickling

我试图将一个JSON对象数组从一个键转换为Scala中的一个对象数组...

以下是代码:

case class RoomList(val rooms : Array[Room])
case class Room(val name : String)

val json = "{\"rooms\" : [{\"name\" : \"Test\"}]}"

println(json.unpickle[RoomList])

这是例外

Exception in thread "main" java.lang.InstantiationException: [Lhipchat.Room;
  at sun.misc.Unsafe.allocateInstance(Native Method)
    at hipchat.HipChat$HipchatRoomListUnpickler1$2$ScalaArray$u005BhipchatRoom$u005DUnpickler1$2$.unpickle(HipChat.scala:46)
    at hipchat.HipChat$HipchatRoomListUnpickler1$2$.unpickle(HipChat.scala:46)
    at hipchat.HipChat.getRooms(HipChat.scala:46)
    at bot.Bot$.main(Bot.scala:11)
    at bot.Bot.main(Bot.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)    

这是RoomList:

val room = new Room("test")
val rooms = Array(room)
val rl = new RoomList(rooms)
println(rl.pickle)

腌渍:

JSONPickle({
  "tpe": "hipchat.RoomList",
  "rooms": {

  }
})

一个腌制的房间:

JSONPickle({
  "tpe": "hipchat.Room",
  "name": "test"
})

2 个答案:

答案 0 :(得分:3)

是的,你说scala / pickling在处理某些集合类型的对象时遇到一些麻烦是正确的。但是,值得注意的是,现在已经修复了一段时间。

鉴于:

case class Room(val name: String)
case class RoomList(val rooms: Array[Room])

还有一些RoomListrl,例如,

val rl = RoomList(Array(Room("foo"), Room("biz"), Room("bang")))

在REPL中,你得到:

scala> val p = rl.pickle
p: scala.pickling.json.JSONPickle = 
JSONPickle({
  "tpe": "RoomList",
  "rooms": {
    "elems": [
      {
      "tpe": "Room",
      "name": "foo"
    },
      {
      "tpe": "Room",
      "name": "biz"
    },
      {
      "tpe": "Room",
      "name": "bang"
    }
    ]
  }
})

我们可以检查REPL以确保pickle / unpickled版本和rl的原始版本具有相同的元素:

scala> rl.pickle.unpickle[RoomList].rooms.sameElements(rl.rooms)
res0: Boolean = true

将此添加到scala/pickling测试套件以及:) https://github.com/scala/pickling/blob/2.10.x/core/src/test/scala/pickling/roomlist-object-array.scala

答案 1 :(得分:0)

“不支持非原始类型的集合”(尚未)

https://github.com/scala/pickling/issues/6

从我所看到的情况来看,scala.pickling在边缘仍然非常粗糙。

此外,默认的pickling格式JSONPickleFormat需要一些元数据(tpe字段),我猜测它不会解析任意JSON对象。