有没有更好的方法将 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
}
}
}