play json 原生支持Map,但仅支持immutable.Map, 为了实现对mutable.Map的支持,可以利用play原生的对immutable.Map的format支持,自定义immutable的 format。
具体实现代码如下:
import play.api.libs.json.{Format, JsSuccess, JsValue, Json, Reads, Writes}
import scala.collection.mutable
object JsonFormat {
//mutable map
def mutableMapReads[V](implicit readsV: Reads[V]):Reads[mutable.Map[String, V]] = (jv:JsValue) => {
JsSuccess(
mutable.Map.empty[String,V] ++ jv.as[Map[String, V]]
)
}
def mutableMapWrites[V](implicit writesV: Writes[Map[String, V]]):Writes[mutable.Map[String, V]] = (mutalMap: mutable.Map[String, V]) => {
Json.toJson( mutalMap.toMap)
}
def mutableMapFormats[V](implicit readsV: Reads[V], writesV: Writes[Map[String, V]]): Format[mutable.Map[String, V]] = Format(mutableMapReads, mutableMapWrites)
implicit val mutableMapFormatLong: Format[mutable.Map[String, Long]] = mutableMapFormats[Long]
implicit val mutableMapFormatSetStr: Format[mutable.Map[String, Set[String]]] = mutableMapFormats[Set[String]]
}