播放2.1 Scala JsValue到Java ObjectNode

时间:2013-08-06 01:06:11

标签: json scala playframework-2.1

有没有更好的方法将scala JsValue(或JsArray)转换为java ObjectNode?

  

Scala的:

object Event {
    def getEventsJson(id: String, limit: Int): Option[JsArray] = {
        val list = getEvents(id, limit)
        val buffer = new scala.collection.mutable.ListBuffer[JsValue]
        list.foreach(e => buffer += Json.toJson(e))
        Json.toJson(buffer.toList) match {
          case x: JsArray => Some(x)
          case _ => None
        }
    }
}
  

爪哇:

ObjectNode result = Json.newObject();
Option<JsArray> eventsOpt = Event.getEventsJson(id, 3);
if (eventsOpt.isDefined()) {
   result.put("events", play.libs.Json.parse(play.api.libs.json.Json.stringify(eventsOpt.get())));
}

**编辑基于@Freidereikhs评论的更改

object Event {
  def getEventsJson(convoId: String, limit: Int): Option[JsArray] = {
    val jsonEvents = getEvents(convoId, limit).map(e => Json.toJson(e))
    Json.toJson(jsonEvents) match {
      case x: JsArray => Some(x)
      case _ => None
    }
  }
}

1 个答案:

答案 0 :(得分:2)

我认为你可以通过替换

来改善这一点
val list = getEvents(id, limit)
val buffer = new scala.collection.mutable.ListBuffer[JsValue]
list.foreach(e => buffer += Json.toJson(e))

val jsonEvents = getEvents.map(e => Json.toJson(e))