[summary] using Json4s to convert Scala objects to Json
Object JsonExample extends App {
Import org.json4s.JsonDSL._
Import org.json4s.jackson.JsonMethods._
/ / the first part is an example of the official website
Case class Winner (id: Long, numbers: List [Int])
Case class Lotto (id: Long, winningNumbers: List [Int], winners: List [Winner], drawDate: Option [java.util.Date])
Val winners = List (Winner (23, List (2,45,34,23,3,5)), Winner (54, List (52,3,12,11,18,22)
Val lotto = Lotto (5, List (2,45,34,23,7,5,3), winners, None)
Val json =
("lotto1"->
("lotto-id"-> lotto.id) ~
("winning-numbers"-> lotto.winningNumbers) ~
("draw-date"-> lotto.drawDate.map (_ .toString)) ~
("winners"->
Lotto.winners.map {w = >
("winner-id"-> w.id) ~
("numbers"-> w.numbers)}))
Println (compact (render (json)
/ / the second part is written with reference to the example on the official website.
Case class StatInfo (min: String, max: String, nullCount: Long, notNullCount: Long, maxLength: Int)
Case class TableStatInfo (tableName: String, count: Long, statInfo: List [StatInfo])
/ / val statInfo = StatInfo ("1", "2", 10,12,202)
Val statInfoList = List (StatInfo ("1", "2", 10,12,202), StatInfo ("1", "2", 10,12202))
Val tableStatInfo = new TableStatInfo ("biz_hotelorder", 0, statInfoList)
Val json1 =
("tableStatInfo"->
("tableName"-> tableStatInfo.tableName) ~
("itemCount"-> tableStatInfo.count) ~
("StatInfo"->
TableStatInfo.statInfo.map {w = >
("min"-> w.min) ~
("max"-> w.max) ~
("nullCount"-> w.nullCount) ~
("notNullCount"-> w.notNullCount) ~
("maxLength"-> w.maxLength)}))
Println (compact (render (json1)
}