Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation error while trying to parse a json array to List[Object] in Scala

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?

like image 405
RafaelTSCS Avatar asked Jul 27 '17 19:07

RafaelTSCS


1 Answers

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, [].

like image 182
Eric Avatar answered Sep 29 '22 10:09

Eric