scala json解析到case类
有时候,需要将从json文件读取程序配置设置,并同步到定义好的一些case类中,这个时候可以使用 io.circe解析json文件,并同步文件字段到定义好的case类
case class Config(
comment:String,
dir:String,
executors:Option[Int],
isOk:Option[Boolean],
isRequires:Boolean,
num:Int,
ratio:Double
)
object JsonDecoding {
def decodingJson(): Unit = {
var jsonStr:String =
"""{
|"comment":"this is comment",
|"dir":"this is dir",
|"executors":10,
|"isOk":true,
|"isRequires":true,
|"num":100,
|"ratio":0.2,
|"test":10000
|}
|
|""".stripMargin
println(jsonStr)
import io.circe.parser._
import io.circe.generic.auto._
val decodeStr = decode[Config](jsonStr) match {
case Left(msg) => throw new RuntimeException(
s"""
|===================
|parser error ${msg}
|""".stripMargin
)
case Right(source) => source
}
println(decodeStr)
}
}
需要两个包:
<dependency>
<groupId>io.circe</groupId>
<artifactId>circe-core_2.11</artifactId>
<version>0.12.0-M3</version>
</dependency>
<dependency>
<groupId>io.circe</groupId>
<artifactId>circe-parser_2.11</artifactId>
<version>0.12.0-M3</version>
</dependency>
<dependency>
<groupId>io.circe</groupId>
<artifactId>circe-generic_2.11</artifactId>
<version>0.12.0-M3</version>
</dependency>