Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

[summary] using Json4s to convert Scala objects to Json

Shulou Source: shulou.com Published: 2022-06-03 07:37:35 09月14日 Update

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)

}

Tags: Example part one part two object Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Redmi Microsoft Huawei MariaDB