1

我有以下情况:

case class Person(id: Int, name: String)
val json = Json.obj("id" -> 1, "name" -> "John", "address"-> "Paris", "contact" -> "1234")

在这里,我想从json中提取额外的(key,value){"address"-> "Paris", "contact" -> "1234"}不属于Person

到目前为止,我已经开发了以下方法:

case class Person(id: Int, name: String)
  val personReads = Json.reads[Person]
  val personWrites = Json.writes[Person]
  val json = Json.obj("id" -> 1, "name" -> "John", "address"-> "Paris", "contact" -> "1234")

  val person: Person = personReads.reads(json).get

  // This person json does not have extra fields 
  val personJson: JsObject = personWrites.writes(person).asInstanceOf[JsObject]

  val extraKeys = json.keys.diff(personJson.keys)

  val extraJson = extraKeys.foldLeft(Json.obj()){(result,key) =>
                            result.+(key -> json.\(key).get)}

  // {"address":"Paris","contact":"1234"}

这可行,但在这里我必须做很多 json 来进行案例类转换。在这种情况下提取额外(键,值)的最佳方法是什么?

4

1 回答 1

3

如果您想让它对任何案例类通用,而不是对 custom 做任何花哨的事情Reads,您可以使用反射或 shapeless 来提取案例类名称,然后从您尝试解析的对象中删除这些名称。

例如,使用反射,这只会创建一次案例类实例,并且根本不需要Writes

import play.api.libs.json._
import scala.reflect.runtime.universe._

def withExtra[A: Reads: TypeTag]: Reads[(A, JsObject)] = {
  val ccFieldNames = typeOf[A].members.collect {
    case m: MethodSymbol if m.isCaseAccessor => m.name.toString
    }.toVector

  for {
    jsObj <- implicitly[Reads[JsObject]]
    a <- implicitly[Reads[A]]
    filteredObj = ccFieldNames.foldLeft(jsObj)(_ - _)
  } yield (a, filteredObj)
}

并像这样使用它:

case class Person(id: Int, name: String)
case class Location(id: Int, address: String)

val json = Json.obj("id" -> 1, "name" -> "John", "address"-> "Paris", "contact" -> "1234")

implicit val pReads = Json.reads[Person]
implicit val lReads = Json.reads[Location]

assert { withExtra[Person].reads(json).get == (
  Person(1, "John"),
  Json.obj("address"-> "Paris", "contact" -> "1234")
) }

assert { withExtra[Location].reads(json).get == (
  Location(1, "Paris"),
  Json.obj("name" -> "John", "contact" -> "1234")
) }

可运行代码在那里可用

于 2017-09-13T08:17:10.197 回答