jag jag - 6 months ago 18
JSON Question

Scala Read JSON file

i want to extract a json file in Scala like this:

val json: JsValue = Json.parse("""
{
"Received":"2015-12-29T00:00:00.000Z",
"Created":"2015-12-29T00:00:00.000Z",
"Location":{
"Created":"2015-12-29T00:00:00.000Z",
"Coordinate":{
"Latitude":45.607807,
"Longitude":-5.712018},
},
"Infos":[],
"DigitalInputs":[{
"TypeId":145,
"Value":false,
"Index":23
}],
}
""")


and this is my Scala code:

import org.apache.flink.api.scala._
import play.api.libs.json._

case class DInputs(
TypeId: Option[Int],
Value: Option[Boolean],
Index: Option[Int]
)

case class myjson (
Received: String,
Created: String,
Location: Option[String],
Infos: Option[String],
DigitalInputs: Option[List[DInputs]],
)

implicit val DInputsRead: Reads[Option[DInputs]] = (
(__ \ "TypeId").readNullable[Int] andThen
(__ \ "Value").readNullable[Boolean] andThen
(__ \ "Index").readNullable[Int]
)(DInputs.apply _)

case Some(json.DInputsRead) => println(json.DInputsRead)


The error in my code:
Expression of type Reads[Option[Int]] doesn´t conform to expected type Reads[Option[DInputs]]


i´m newbie and don´t understand where is the problem, and i don´t know if this is the best way to read a json file, so any help is appreciate.Thank you.

Answer

Reads should be defined for DInputs, not for Option[DInputs]. The second problem is that you're using andThen instead of and. This is how your Reads should look like:

import play.api.libs.functional.syntax._
import play.api.libs.json._

implicit val DInputsReads: Reads[DInputs] = (
  (__ \ "TypeId").readNullable[Int] and
  (__ \ "Value").readNullable[Boolean] and
  (__ \ "Index").readNullable[Int]
)(DInputs.apply _)