简体   繁体   English

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

[英]How to remove List() and escape characters from response JSON in Scala

I have the following function that takes in a JSON input and validates it against a JSON-Schema using the "com.eclipsesource" %% "play-json-schema-validator" % "0.6.2" library. 我具有以下函数,该函数接受JSON输入并使用"com.eclipsesource" %% "play-json-schema-validator" % "0.6.2"库针对JSON-Schema对其进行"com.eclipsesource" %% "play-json-schema-validator" % "0.6.2" Everything works fine expect for when I get an invalid JSON, I try to collect all violations into a List and later return that list along with the response JSON. 当我收到无效的JSON时,一切正常,我尝试将所有违规行为收集到一个List ,然后将该列表与响应JSON一起返回。 However my List is encoded with List() and also has escape characters. 但是我的列表是用List()编码的,并且还具有转义字符。 I want to have the response JSON look like this: 我希望响应JSON如下所示:

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

Instead of this: (This is what I am getting right now) 代替这个:(这就是我现在得到的)

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

And here's the actual function for JSON validation 这是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)
        }
      )
    }

  }

UPDATE 1 更新1

I get this after using Json.obj() 我在使用Json.obj()之后得到了这个

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

What you want is a JSON array, but by calling .toString() on your list, you're actually passing a string. 您想要的是一个JSON数组,但是通过在列表上调用.toString() ,您实际上是在传递字符串。 Play has an implicit serializer for List s to JSON arrays, so you actually just have to do less then what you already did - you can just remove the toString() part from violatesList.toString() . Play具有一个List到JSON数组的隐式序列化器,因此实际上您要做的事情比已经做的要少-您只需从violatesList.toString() toString()删除toString()部分即可。

In addition, don't create a map for your JSON and then convert it to a JSON, you can use Json.obj with a very similar syntax instead: 另外,不要为您的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)

Regarding your escaped quotes, I suppose it's because transactionID and msgs are JsString s, so when you convert them with toString() the quotes are included. 关于转义的引号,我想是因为transactionIDmsgsJsString ,所以当您使用toString()转换它们时,引号也包括在内。 Just remove the toString everywhere and you'll be fine. 只需在所有地方删除toString ,就可以了。

I got the escape characters removed by modifying this line: 我通过修改这一行删除了转义字符:

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

TO: 至:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM