oortcloud_domicile
oortcloud_domicile

Reputation: 850

parsing a json file using play json

I am reading a HDFS sequence file and which is of [Long, String] lets call each record as message. message._2 is a json string and i am trying to parse it using play json library but i get the following error when i do it.

Error:

found   : Seq[play.api.libs.json.JsValue]
required: String

Code:

val jsonString = message._2.toString();
val json = Json.parse(jsonString);
code = (json(0) \\ "code"); -- > Error is pointing to \\ on this line

Upvotes: 0

Views: 202

Answers (1)

Serhii Sokolenko
Serhii Sokolenko

Reputation: 6164

The error message says that (json(0) \\ "code") returns Seq[play.api.libs.json.JsValue], and you're trying to assign this value to the variable code of type String.

So, you may want to do this:

code = (json(0) \\ "code").head.as[String]

which will get the first item of a list and convert JsValue to String.

Update

As @cchantep suggested, the use of head is not safe, so for better safety you can do it with headOption, but the result type will be Option[String]:

val code: Option[String] =
    (json \\ "code").headOption.map(_.as[String])

and even more safe code will look like this:

val code: Option[String] =
    (json \\ "code").headOption.flatMap(_.asOpt[String])

Upvotes: 1

Related Questions