[关闭]
@xtccc 2016-02-24T23:18:00.000000Z 字数 1437 阅读 7308

YAML解析

给我写信
GitHub

此处输入图片的描述

开发技巧


1. YAML文件的结构


参考 Working with YAML: Configuration Files




2. Snake Yaml


通过SnakeYaml,可以在Scala/Java代码中解析一个yaml文件。

假设一个yaml文件内容如下:

  1. name: CCC
  2. age: 26
  3. city: TRUE
  4. height: 0.015
  5. # details 是一个map
  6. details:
  7. first_name: chuchu
  8. last_name: chen
  9. home: 泰兴

下面,我们将展示如何解析这个yaml文件

2.1 将yaml转换成Bean

一个yaml实际上是一个Map结构,它可以对应到一个实现定义的Bean,现在我们定义一个名为SpeedyConfig的Bean:

  1. import scala.beans.BeanProperty
  2. class SpeedyConfig extends Serializable {
  3. @BeanProperty var name: String = "Unknown name"
  4. @BeanProperty var age: Int = -1
  5. @BeanProperty var city: String = "Unknown city"
  6. @BeanProperty var height: Float = 0
  7. @BeanProperty var details: util.HashMap[String, Object] = null
  8. }



然后,将yaml文件的内容填充到这个Bean中:

  1. val stream = getClass.getResourceAsStream("/sample.yaml")
  2. val yaml = new Yaml(new Constructor(classOf[SpeedyConfig]))
  3. val config: SpeedyConfig = yaml.load(stream).asInstanceOf[SpeedyConfig]
  4. println(s"${config.getName}, ${config.getAge}, ${config.getCity}")
  5. println(config.getDetails)

输出如下:
QQ20160224-0@2x.png-20.1kB


2.2 将yaml转化为HashMap结构

  1. val stream = getClass.getResourceAsStream("/sample.yaml")
  2. val yaml = new Yaml()
  3. val obj = yaml.load(stream).asInstanceOf[util.HashMap[String, Object]]
  4. val stringValue = obj.get("name")
  5. val intValue = obj.get("age").asInstanceOf[Int]
  6. val booleanValue = obj.get("city").asInstanceOf[Boolean]
  7. val floatValue = obj.get("height").asInstanceOf[Double].toFloat
  8. val mapValue = obj.get("details").asInstanceOf[util.HashMap[String, Object]]
  9. println(s"name -> ${stringValue}, " +
  10. s"age -> ${intValue}, " +
  11. s"city -> ${booleanValue}, " +
  12. s"height -> ${floatValue}")
  13. println(s"map -> ${mapValue}")

运行输出为:
QQ20160224-1@2x.png-23.5kB




添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注