2

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

斯卡拉:

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

1 回答 1

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))
于 2013-08-28T07:40:44.667 回答