我想在Scala中提取一个json文件,如下所示:
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
}],
}
""")
这是我的Scala代码:
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)
我的代码中的错误:Expression of type Reads[Option[Int]] doesn´t conform to expected type Reads[Option[DInputs]]
我是新手并且不明白问题出在哪里,我不知道这是否是阅读json文件的最佳方式,所以任何帮助都是值得欣赏的。谢谢。
答案 0 :(得分:0)
您的输入和解决方案存在一些问题:
Location
对象之后和DigitalInputs
对象之后。您可以验证您的JSON here。Reads
方法可以显着缩短Json.reads
个实例。Reads
课程的myjson
个实例。Location
对象的案例类。以下是将输入JSON解析为常规Scala案例类的完整示例:
import play.api.libs.json.Json
case class MyJson(Received: String,
Created: String,
Location: Option[Location],
Infos: Option[List[String]],
DigitalInputs: Option[List[DigitalInputs]])
case class Location(Created: String,
Coordinate: Coordinate)
case class Coordinate(Latitude: Double,
Longitude: Double)
case class DigitalInputs(TypeId: Option[Int],
Value: Option[Boolean],
Index: Option[Int])
implicit val digitalInputsReads = Json.reads[DigitalInputs]
implicit val coordinateReads = Json.reads[Coordinate]
implicit val locationReads = Json.reads[Location]
implicit val myJsonReads = Json.reads[MyJson]
val inputJson = 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
| }
| ]
|}
""".stripMargin
)
val myJsonInstance: MyJson = inputJson.as[MyJson]
val longitude: Option[Double] = myJsonInstance.Location.map(_.Coordinate.Longitude) // Some(-5.712018)
val typeId: Option[Int] = myJsonInstance.DigitalInputs.flatMap(_.headOption.flatMap(_.TypeId)) // Some(145)