如何从Scala中的响应JSON中删除List()和转义字符

时间:2016-01-20 15:58:48

标签: json scala playframework

我有以下函数接受JSON输入并使用"com.eclipsesource" %% "play-json-schema-validator" % "0.6.2"库对JSON-Schema进行验证。当我得到一个无效的JSON时,一切正常。我尝试将所有违规行为收集到List中,然后将该列表与响应JSON一起返回。但是,我的列表使用List()进行编码,并且还具有转义字符。我希望响应JSON看起来像这样:

{
  "transactionID": "123",
  "status": "error",
  "description": "Invalid Request Received",
  "violations": ["Wrong type. Expected integer, was string.", "Property action missing"]
}

而不是:(这就是我现在所得到的)

{
  "transactionID": "\"123\"",
  "status": "error",
  "description": "Invalid Request Received",
  "violations": "List(\"Wrong type. Expected integer, was string.\", \"Property action missing\")"
}

这里是JSON验证的实际功能

def validateRequest(json: JsValue): Result = {

    {
      val logger = LoggerFactory.getLogger("superman")
      val jsonSchema = Source.fromFile(play.api.Play.getFile("conf/schema.json")).getLines.mkString
      val transactionID = (json \ "transactionID").get
      val result: VA[JsValue] = SchemaValidator.validate(Json.fromJson[SchemaType](
        Json.parse(jsonSchema.stripMargin)).get, json)

      result.fold(
        invalid = { errors =>

          var violatesList = List[String]()
          var invalidError = Map("transactionID" -> transactionID.toString(), "status" -> "error", "description" -> "Invalid Request Received")
          for (msg <- (errors.toJson \\ "msgs"))
            violatesList = (msg(0).get).toString() :: violatesList
          invalidError += ("violations" -> (violatesList.toString()))
          //TODO: Make this parsable JSON list
          val errorResponse = Json.toJson(invalidError)
          logger.error("""Message="Invalid Request Received" for transactionID=""" + transactionID.toString() + "errorResponse:" + errorResponse)
          BadRequest(errorResponse)

        },

        valid = {
          post =>
            db.writeDocument(json)
            val successResponse = Json.obj("transactionID" -> transactionID.toString, "status" -> "OK", "message" -> ("Valid Request Received"))
            logger.info("""Message="Valid Request Received" for transactionID=""" + transactionID.toString() + "jsonResponse:" + successResponse)
            Ok(successResponse)
        }
      )
    }

  }

更新1

使用Json.obj()

后得到这个
{
  "transactionID": "\"123\"",
  "status": "error",
  "description": "Invalid Request Received",
  "violations": [
    "\"Wrong type. Expected integer, was string.\"",
    "\"Property action missing\""
  ]
}

2 个答案:

答案 0 :(得分:1)

你想要的是一个JSON数组,但是通过调用列表中的.toString(),你实际上传递了一个字符串。 Play有List到JSON数组的隐式序列化程序,所以你实际上只需要做的就是你已经做过的事情 - 你可以从toString()删除violatesList.toString()部分。

此外,不要为您的JSON创建地图,然后将其转换为JSON,您可以使用具有非常相似语法的Json.obj

val invalidError = Json.obj("transactionID" -> transactionID, "status" -> "error", "description" -> "Invalid Request Received")
for (msg <- (errors.toJson \\ "msgs"))
  violatesList = (msg(0).get) :: violatesList
val errorResponse = invalidError ++ Json.obj("violations" -> violatesList)

关于您的转义引号,我认为这是因为transactionIDmsgsJsString,所以当您使用toString()进行转换时,引号包括在内。只需删除toString无处不在,您就可以了。

答案 1 :(得分:1)

我通过修改此行删除了转义字符:

violatesList = (msg(0).get).toString() :: violatesList

TO:

violatesList = (msg(0).get).as[String] :: violatesList