scala 自带json模块

import scala.util.parsing.json
不用第三方包, 解析和拼接都不好控制

# map -> scala.util.parsing.json.JSONObject
scala.util.parsing.json.JSONObject(map).toString()
# list -> scala.util.parsing.json.JSONArray
scala.util.parsing.json.JSONArray(list).toString()
# json -> map
import scala.util.parsing.json.JSON
import scala.util.parsing.json.JSONObject

val colors:Map[String,Object]  = Map("red" -> "123456", "azure" -> "789789")
val json = JSONObject(colors)
println(json)
val jsonMap = JSON.parseFull(json.toString).get.asInstanceOf[Map[String,Object]]
println(jsonMap)
/* ---------------------------------------- */
val jsonStr = """{"username":"Ricky", "age":"21"}"""
val jsonValue = JSON.parseFull(jsonStr)
val jsonObj = jsonValue match {
    case Some(map:Map[String, Any]) => map.asInstanceOf[Map[String,String]]
    case _ => println("ERROR jsonStr")
}
val username = jsonObj.get("username")

import scala.util.parsing.json.JSON

val jsonStr = """{"username":"Ricky", "attribute":{"age":21, "weight": 60}}"""
val jsonValue = JSON.parseFull(jsonStr)

val jsonObj = jsonValue match {
    case Some(map:Map[String, Any]) => map
    case other => println("Error jsonStr")
}

// 将attribute转换成Map
val attrObj = jsonObj.get("attribute").get.asInstanceOf[Map[String, String]]

val age = attrObj.get("age")

json4s

<dependency>
  <groupId>org.json4s</groupId>
  <artifactId>json4s-jackson_${scala.version}</artifactId>
  <version>{latestVersion}</version>
</dependency>

官网地址: https://github.com/json4s/json4s
生成和解析json的过程都有些麻烦, 不能直接生成一个map或list
JObject解析, 但json和xml格式可以互转

# json -> List
import org.json4s._
import org.json4s.jackson.JsonMethods._

var temp = new ListBuffer[(String, Long, Int)]
val dataLog = parse(x.toString)
              for {JObject(child) <- dataLog
                   JField("url", JString(url)) <- child
                   JField("time", JInt(time)) <- child
                  JField("origin", JInt(origin)) <- child
                if origin.toDouble.toInt >= 1
              }
temp += Tuple4(url,
                           time.toDouble.toLong,
                            origin.toString.toDouble.toInt)

样例类解析

scala> import org.json4s._
scala> import org.json4s.jackson.JsonMethods._

scala> implicit val formats = DefaultFormats // Brings in default date formats etc.

scala> case class Child(name: String, age: Int, birthdate: Option[java.util.Date])
scala> case class Address(street: String, city: String)
scala> case class Person(name: String, address: Address, children: List[Child])

scala> val json = parse("""
         { "name": "joe",
           "address": {
             "street": "Bulevard",
             "city": "Helsinki"
           },
           "children": [
             {
               "name": "Mary",
               "age": 5,
               "birthdate": "2004-09-04T18:06:22Z"
             },
             {
               "name": "Mazy",
               "age": 3
             }
           ]
         }
       """)

scala> json.extract[Person]
res0: Person = Person(joe,Address(Bulevard,Helsinki),List(Child(Mary,5,Some(Sat Sep 04 18:06:22 EEST 2004)), Child(Mazy,3,None)))

scala> val addressJson = json  \ "address"  // Extract address object
scala> addressJson.extract[Address]
res1: Address = Address(Bulevard,Helsinki)

scala> (json \ "children").extract[List[Child]]  // Extract list of objects
res2: List[Child] = List(Child(Mary,5,Some(Sat Sep 04 23:36:22 IST 2004)), Child(Mazy,3,None))

json拼接

# map -> json
object JsonExample extends App {
  import org.json4s._
  import org.json4s.JsonDSL._
  import org.json4s.jackson.JsonMethods._

  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 =
    ("lotto" ->
      ("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)))
}
scala> JsonExample
{"lotto":{"lotto-id":5,"winning-numbers":[2,45,34,23,7,5,3],"winners":
[{"winner-id":23,"numbers":[2,45,34,23,3,5]},{"winner-id":54,"numbers":[52,3,12,11,18,22]}]}}

gson

https://blog.csdn.net/shuaidan19920412/article/details/79356440

json <-> case class

import com.google.gson.Gson
case class Student( name:String , no: String )
  val gson = new Gson
    val student = Student("张三", "100")
    val str = gson.toJson(student, classOf[Student])
    println(str)
    val student2 = gson.fromJson(str, classOf[Student])
    println(student2)

json <-> javaMap

// 注意这里只能是java的HashMap 或者其子类LinkedHashMap, TreeMap
// 经实验 scala的Map 以及 java.util.Map 都会有问题的
val map = new java.util.HashMap[String, Object]()
map.put("abc", List(s1,s2).toArray)
val gson = new Gson()
println( gson.toJson(map) )
判断json
def isGoodJson(json: String):Boolean = {

   if(null == json) {
     return false
   }
   val result =  JSON.parseFull(json) match {
     case Some(_:  Map[String, Any]) => true
     case None => false
     case _ => false
   }
   result
 }

spray-json

https://github.com/spray/spray-json

<dependency>
      <groupId>io.spray</groupId>
      <artifactId>spray-json_${scala.version}</artifactId>
      <version>1.3.2</version>
</dependency>
val json = JsonParser(result).asJsObject()
println(json.getFields("name"))

原文链接: https://json.im/jichu/scala-json.html