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