Last active
April 23, 2016 15:30
-
-
Save todokr/61cfb58bc6de309db6798f93b9e4f26e to your computer and use it in GitHub Desktop.
hjson-javaをScalaから利用するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.ShunsukeTadokoro | |
import org.hjson._ | |
import play.api.libs.json.Json | |
object HjsonSample { | |
def main(args: Array[String]) { | |
val hjson = | |
""" | |
|{ | |
| # コメントが書ける | |
| | |
| // これもコメント | |
| | |
| /* | |
| * 複数行の | |
| * コメントも | |
| * 大丈夫 | |
| */ | |
| | |
| // keyやvalueをクオートで囲む必要がない | |
| // 末尾のカンマも不要 | |
| name: Shunsuke Tadokoro | |
| | |
| // 配列もカンマ不要 | |
| color: [ | |
| red | |
| green | |
| blue | |
| ] | |
| | |
| // valueにカンマが入っていてもOK | |
| hello: Hello, HJSON! | |
| | |
| // エスケープは不要 | |
| regex: ^\d{2,4}\.\w+?-\d+ | |
| html: <h1>HTML Element</h1> | |
| | |
| // シングルクオート3つで囲むと改行を含められる | |
| poem: | |
| ''' | |
| 若さ 若さってなんだ ふりむかないことさ | |
| 愛ってなんだ ためらわないことさ | |
| ''' | |
|} | |
""".stripMargin | |
// JSONオブジェクトとしてパース | |
val jsonObj = JsonValue.readHjson(hjson).asObject | |
println("Name: " + jsonObj.get("name").asString) | |
println("Colors: " + jsonObj.get("color").asArray) | |
println("Greet: " + jsonObj.get("hello").asString) | |
println("Regex: " + jsonObj.get("regex").asString) | |
println("HTML: " + jsonObj.get("html").asString) | |
// 普通のJSON文字列にパースすることもできるので、そのあとはお好みのJSONパーサーで扱える | |
val normalJsonStr = JsonValue.readHjson(hjson).toString | |
val normalJson = Json.parse(normalJsonStr) | |
println((normalJson \ "poem").as[String]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment