jag jag - 1 year ago 235
JSON Question

Scala Read JSON file

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

val json: JsValue = Json.parse("""

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 Source

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 _)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download