如何从JsonPatch读取路径值?

时间:2018-10-02 14:10:38

标签: scala spray-json

示例:

我有以下示例代码:

import spray.json._
import gnieh.diffson.sprayJson._

val patchString1 = """[{"op": "replace", "path": "/emails","value":["xxx@yyy.com"] }]"""

val patchString2 = """[{"op": "replace", "path": "/emails/1","value":"xxx@yyy.com" }]"""

val patchOps1 = JsonPatch.parse(patchString1)
patchOps1.foreach(op => {
  println(op.path)  <<<< this prints /emails 
  println(op)     <<< this prints Replace(/emails,["xxx@yyy.com"],None)
})

我的问题是如何在此处读取值,即“ xxx@yyy.com”。

1 个答案:

答案 0 :(得分:0)

import spray.json._
case class IndividualMail(op: String, path: String, value: List[String])

object MailProtocol extends DefaultJsonProtocol {
  implicit object IndividualMailJsonFormat extends RootJsonFormat[IndividualMail] {

    def read(value: JsValue): IndividualMail = {
      value.asJsObject.getFields("op", "path", "value") match {
        case Seq(JsString(op), JsString(path), JsArray(value)) => IndividualMail(op, path, value.toList.map(_.toString()))
        case Seq(JsString(op), JsString(path), JsString(value)) => IndividualMail(op, path, List(value))
        case _ => throw deserializationError("Cannot Deserialize")
      }
    }

    def write(obj: IndividualMail): JsValue = {
      JsObject("op" -> JsString(obj.op),
        "path" -> JsString(obj.path),
        "value" -> JsArray(obj.value.map(JsString(_)).toVector)
      )
    }
  }
}
import MailProtocol._

val patchString1 = """[{"op": "replace", "path": "/emails","value":["xxx@yyy.com"] }]"""
val patchString2 = """[{"op": "replace", "path": "/emails/1","value":"xxx@yyy.com" }]"""

val a = patchString1.parseJson.convertTo[List[IndividualMail]]
val b = patchString2.parseJson.convertTo[List[IndividualMail]]

JSON中字段值的问题在于它本质上是不确定的,因为值可以是List或普通字符串。由于这种性质,您可能需要定义自己的自定义MailProtocol,使用它可以获取所需的值。