5

I have a method that returns a JsArray of a type Foo.

To process the response, I am doing the following:

val foos : List[Foo] = Json.toJson(result).as[List[Foo]]

While debugging, I could see that the result is comming as:

"[]"

and it is generated by the code:

Ok(Json.toJson(foos))

Where foos is a List[Foo]

But I am getting the error:

[JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsarray,WrappedArray())))))]

I've tried many ways, but can't solve this.

What I am doing wrong?

3
  • What does result look like? Also, Object is Java, while the equivalent in Scala is AnyRef.
    – sheunis
    Jul 27, 2017 at 19:46
  • as Object I mean Foo.
    – RafaelTSCS
    Jul 27, 2017 at 19:46
  • and the result of the method is "[]", since it is an empty List
    – RafaelTSCS
    Jul 27, 2017 at 19:48

2 Answers 2

6

You're most likely looking for Json.parse, rather than Json.toJson.

import play.api.libs.json.Json

scala> Json.toJson("[]")
res0: play.api.libs.json.JsValue = "[]"

scala> Json.parse("[]")
res1: play.api.libs.json.JsValue = []

Trying to convert res0 to a List[Foo] doesn't work because you're trying to convert the string "[]" rather than than the same string without quotation marks, [].

4

It seems like you have it the wrong way around. Json.toJson(value) is used to convert from a Scala object to a JSON value. You are using it incorrectly to try and read a JSON body and convert it to a Scala object. You probably want to do something like this:

val foos : JsResult[List[Foo]] = result.validate[List[Foo]]

where result is your JSON value.

Look at this, under the 'JsValue to a model' section:

https://www.playframework.com/documentation/2.6.x/ScalaJson

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.