【发布时间】:2016-01-21 01:18:26
【问题描述】:
我有以下函数,它接收 JSON 输入并使用 "com.eclipsesource" %% "play-json-schema-validator" % "0.6.2" 库根据 JSON 模式对其进行验证。当我收到无效的 JSON 时,一切正常,我尝试将所有违规行为收集到 List 中,然后将该列表与响应 JSON 一起返回。但是,我的 List 是用 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\""
]
}
【问题讨论】:
标签: json scala playframework