user12210941
user12210941

Reputation:

PlayJSON in Scala

I am trying to familiarize myself with the PlayJSON library. I have a JSON formatted file like this:

{
  "Person": [
    {
      "name": "Jonathon",
      "age": 24,
      "job": "Accountant"
    }
  ]
}

However, I'm having difficulty with parsing it properly due to the file having different types (name is a String but age is an Int). I could technically make it so the age is a String and call .toInt on it later but for my purposes, it is by default an integer.

I know how to parse some of it:

import play.api.libs.json.{JsValue, Json}

val parsed: JsValue = Json.parse(jsonFile) //assuming jsonFile is that entire JSON String as shown above

val person: List[Map[String, String]]  = (parsed \ "Person").as[List[Map[String, String]]]

Creating that person value throws an error. I know Scala is a strongly-typed language but I'm sure there is something I am missing here. I feel like this is an obvious fix too but I'm not quite sure.

The error produced is:

JsResultException(errors:List(((0)/age,List(JsonValidationError(List(error.expected.jsstring),WrappedArray())))

Upvotes: 0

Views: 102

Answers (1)

Tomer Shetah
Tomer Shetah

Reputation: 8529

The error you are having, as explained in the error you are getting, is in casting to the map of string to string. The data you provided does not align with it, because the age is a string. If you want to keep in with this approach, you need to parse it into a type that will handle both strings and ints. For example:

(parsed \ "Person").validate[List[Map[String, Any]]]

Having said that, as @Luis wrote in a comment, you can just use case class to parse it. Lets declare 2 case classes:

case class JsonParsingExample(Person: Seq[Person])
case class Person(name: String, age: Int, job: String)

Now we will create a formatter for each of them on their corresponding companion object:

object Person {
  implicit val format: OFormat[Person] = Json.format[Person]
}

object JsonParsingExample {
  implicit val format: OFormat[JsonParsingExample] = Json.format[JsonParsingExample]
}

Now we can just do:

Json.parse(jsonFile).validate[JsonParsingExample]

Code run at Scastie.

Upvotes: 1

Related Questions