toJson不起作用,但即使两者都返回JsValue,解析也会起作用

时间:2018-06-12 08:04:21

标签: playframework-2.6

我在单元测试中观察到一种奇怪的行为。在收到来自服务器的响应后,我将正文转换为String,然后转换为JsValue,然后转换为我的模型。我注意到,如果我使用Json.toJson,那么我的JsValue模型代码不起作用,但如果我使用Json.parse则会这样做!为什么呢?

不起作用的代码

val request = FakeRequest("POST","ws/users/signup")
      println("sending request",request)
      val result:Future[Result] = controller.signupUser(request)
      val bodyAsString = contentAsString(result) //get body as string
      println("body as String: "+bodyAsString)
      val bodyAsJson = Json.toJson[String](bodyAsString) //convert to JsValue
      println("body as json:"+bodyAsJson)
      val jsonResultError:JsonResult = bodyAsJson.as[JsonResult] //convert to model
      println("jsonResultError: "+jsonResultError)
      (status(result) mustBe OK )
      (jsonResultError.message mustBe incorrectBodyTypeDescription)

我收到错误

body as String: {"result":"error","additional-info":"Incorrect body type. Body type must be JSON"}
body as json:"{\"result\":\"error\",\"additional-info\":\"Incorrect body type. Body type must be JSON\"}"

JsResultException(errors:List((/additional-info,List(JsonValidationError(List(error.path.missing),WrappedArray()))), (/result,List(JsonValidationError(List(error.path.missing),WrappedArray())))))
play.api.libs.json.JsResultException: JsResultException(errors:List((/additional-info,List(JsonValidationError(List(error.path.missing),WrappedArray()))), (/result,List(JsonValidationError(List(e

但如果我使用parse,则代码可以正常工作

val bodyAsJson = Json.parse(bodyAsString)

body as String: {"result":"error","additional-info":"Incorrect body type. Body type must be JSON"}
body as json:{"result":"error","additional-info":"Incorrect body type. Body type must be JSON"}
jsonResultError: JsonResultError(Incorrect body type. Body type must be JSON)

我注意到在第一种情况下,还有一个\",但我不知道它为什么会出现

代码不起作用

body as json:"{\"result\":\"error\",\"additional-info\":\"Incorrect body type. Body type must be JSON\"}"

有效的代码

body as json:{"result":"error","additional-info":"Incorrect body type. Body type must be JSON"}

0 个答案:

没有答案