0

我正在尝试将 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)    

这是一个房间列表:

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"
})
4

2 回答 2

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 以确保腌制/未腌制版本和原始版本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

于 2013-09-11T17:01:01.773 回答
0

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

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

据我所见,scala.pickling边缘仍然非常粗糙。

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

于 2013-08-01T12:50:04.910 回答