实例代码
import cn.hutool.json.JSONUtil
import com.google.gson.Gson
object EntitytoJsonTest {
def main(args: Array[String]): Unit = {
val gson = new Gson
val people = JJ("gl", 12, List("basketball", "baseball"),
Map("k1" -> "v1", "k2" -> "v2"))
println("gson======================")
val jsonStr = gson.toJson(people)
println(jsonStr)
println(gson.toJson(List("123","234","455")))
println(gson.toJson(List("123","234","455")))
println(gson.toJson(Map("k1" -> "v1", "k2" -> "v2")))
println("json4s======================")
import org.json4s._
import org.json4s.jackson.Serialization._
import org.json4s.jackson.Serialization
implicit val formats = Serialization.formats(NoTypeHints)
val m = Map(
"name" -> "john doe",
"age" -> 18,
"hasChild" -> true,
"childs" -> List(
Map("name" -> "dorothy", "age" -> 5, "hasChild" -> false),
Map("name" -> "bill", "age" -> 8, "hasChild" -> false)))
val s:String = write(m)
println(s)
val s1 = write(people)
println(s1)
println("JSONUtil======================")
println(JSONUtil.toJsonStr(people))
println(JSONUtil.toJsonPrettyStr(s1))
}
}
case class JJ(var name: String, var age: Int, var hobbies: List[String]
, var skills: Map[String, String])
运行结果
gson======================
{"name":"gl","age":12,"hobbies":{},"skills":{}}
{"head":"123","tl":{}}
{"head":"123","tl":{}}
{"key1":"k1","value1":"v1","key2":"k2","value2":"v2"}
json4s======================
{"name":"john doe","age":18,"hasChild":true,"childs":[{"name":"dorothy","age":5,"hasChild":false},{"name":"bill","age":8,"hasChild":false}]}
{"name":"gl","age":12,"hobbies":["basketball","baseball"],"skills":{"k1":"v1","k2":"v2"}}
JSONUtil======================
{}
标签:Map,name,val,scala,JSONUtil,gson,println,age
From: https://www.cnblogs.com/iullor/p/17531985.html