我有以下情况:
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 来进行案例类转换。在这种情况下提取额外(键,值)的最佳方法是什么?