@xtccc
2016-02-24T23:18:00.000000Z
字数 1437
阅读 7308
开发技巧
参考 Working with YAML: Configuration Files
通过SnakeYaml,可以在Scala/Java代码中解析一个yaml文件。
假设一个yaml文件内容如下:
name: CCC
age: 26
city: TRUE
height: 0.015
# details 是一个map
details:
first_name: chuchu
last_name: chen
home: 泰兴
下面,我们将展示如何解析这个yaml文件
一个yaml实际上是一个Map结构,它可以对应到一个实现定义的Bean,现在我们定义一个名为SpeedyConfig的Bean:
import scala.beans.BeanProperty
class SpeedyConfig extends Serializable {
@BeanProperty var name: String = "Unknown name"
@BeanProperty var age: Int = -1
@BeanProperty var city: String = "Unknown city"
@BeanProperty var height: Float = 0
@BeanProperty var details: util.HashMap[String, Object] = null
}
然后,将yaml文件的内容填充到这个Bean中:
val stream = getClass.getResourceAsStream("/sample.yaml")
val yaml = new Yaml(new Constructor(classOf[SpeedyConfig]))
val config: SpeedyConfig = yaml.load(stream).asInstanceOf[SpeedyConfig]
println(s"${config.getName}, ${config.getAge}, ${config.getCity}")
println(config.getDetails)
输出如下:
val stream = getClass.getResourceAsStream("/sample.yaml")
val yaml = new Yaml()
val obj = yaml.load(stream).asInstanceOf[util.HashMap[String, Object]]
val stringValue = obj.get("name")
val intValue = obj.get("age").asInstanceOf[Int]
val booleanValue = obj.get("city").asInstanceOf[Boolean]
val floatValue = obj.get("height").asInstanceOf[Double].toFloat
val mapValue = obj.get("details").asInstanceOf[util.HashMap[String, Object]]
println(s"name -> ${stringValue}, " +
s"age -> ${intValue}, " +
s"city -> ${booleanValue}, " +
s"height -> ${floatValue}")
println(s"map -> ${mapValue}")
运行输出为: