Scala如何处理(多级)JSON字符串

时间:2023-02-08 23:13:44

Scala如何处理(多级)JSON字符串


1.JSON.parseFull

  • 简单JSON格式

    import scala.util.parsing.json.JSON

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

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

    val username = jsonObj.get("username")
  • 多级JSON字符串

    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")

2.spary-json

DefaultJsonProtocol

spary-json定义了以下数据类型, 可以根据JSON字符串定义格式

  • Byte, Short, Int, Long, Float, Double, Char, Unit, Boolean
  • String, Symbol
  • BigInt, BigDecimal
  • Option, Either, Tuple1 - Tuple7
  • List, Array
  • immutable.{Map, Iterable, Seq, IndexedSeq, LinearSeq, Set, Vector}
  • collection.{Iterable, Seq, IndexedSeq, LinearSeq, Set}
  • JsValue

    • 简单JSON格式
    import spray.json._
    import DefaultJsonProtocol._

    val jsonStr = """{"username":"Ricky", "age":"21"}"""
    val jsonObj = jsonStr.parseJson.convertTo[Map[String, String]]
    val username = jsonObj.get("username")
    • 多级JSON格式
    import spary.json._
    import DefaultJsonProtocol._

    val jsonStr = """{"username":"Ricky", "attribute":{"age":21, "weight": 60}}"""

    // 这里的JsValue相当于Scala中的Any
    // 当JSON字符串格式不一定是可以用这种方法
    val jsonObj = jsonStr.parseJson.convertTo[Map[String, JsValue]]
    val attrObj = jsonObj.get("attribute").get.asJsObject().
    convertTo[Map[String,String]]

    val username = jsonObj.getOrElse("username", "RickyHuo").toString

    println(username)
    // "username"
    // 这里需要注意, JsValue中字符串自带双引号, 之后使用需要手动去除

YourJsonProtocol(自定义协议)

  • 简单JSON格式
case class Person(username: String, age:Int)

object MyJsonProtocol extends DefaultJsonProtocol {
implicit val personFormat = jsonFormat2(Person)
}

import MyJsonProtocol._
import spray.json._

val jsonStr = """{"username":"Ricky", "age":21}"""
val jsonObj = jsonStr.parseJson.convertTo[Person]

val username = jsonObj.username
  • 多级JSON格式
    待验证
case class Person(username: String, attribute:Attribute)
case class Attribute(age: Int, weight: Int)

object MyJsonProtocol extends DefaultJsonProtocol {
implicit val personFormat = jsonFormat2(Person)
}

import MyJsonProtocol._
import spray.json._

val jsonStr = """{"username":"Ricky", "attribute": {"age":12, "weight":60}}"""
val jsonObj = jsonStr.parseJson.convertTo[Person]

val username = jsonObj.username

3.Reference

spary-json