scala class、Map、List 转换成Json(Gson、json4s、JSONUtil)

pom 依赖引入

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>org.json4s</groupId>
            <artifactId>json4s-core_2.12</artifactId>
            <version>3.6.6</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.3</version>
        </dependency>

实例代码

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"),scala.collection.mutable.ListBuffer("xiaomi","tuanzi"))

    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],
              var friends: scala.collection.mutable.ListBuffer[String])

运行结果

gson======================
{"name":"gl","age":12,"hobbies":{},"skills":{},"friends":{"scala$collection$mutable$ListBuffer$$start":{},"last0":{"head":"tuanzi","tl":{}},"exported":false,"len":2}}
{"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"},"friends":["xiaomi","tuanzi"]}
JSONUtil======================
{}

经测试:
Gson:支持普通对象属性转换,不支持对不可变的List、Map转换、支持对mutable.ListBuffer转换,但不友好
hutool.JSONUtil:白搭
json4s:均支持,万能,推荐使用

posted @ 2023-07-06 14:03  iullor  阅读(354)  评论(0编辑  收藏  举报