比如有一个复杂对象:
Map[Int, Map[Int, Double]]
需要将其转为JSON保存,之后再读取使用,试了几种方法,最后的方案是:
1、定义case class
2、所有的数据类型都转为String(避免不必要的麻烦,至少Map的key都要为String,不然会报错scala.MatchError)
3、Map必须是immutable.Map
代码如下
1、转json
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization._
import org.json4s.jackson.Serialization
case class WOE(col: String, woe: Map[String, String])
implicit val formats = Serialization.formats(NoTypeHints)
val testMap = Map[String, String]()
testMap += ("1" -> "1.1")
val a = WOE("1", immutable.Map(testMap.toList:_*))
println(write(a))
输出{"col":"1","woe":{"1":"1.1"}}
2、解析json
implicit val formats = Serialization.formats(NoTypeHints)
val js =
"""
{"col":"1","woe":{"1":"1.1"}}
"""
val ab = parse(js).extract[WOE]
println(write(ab))
如果是List也可以
implicit val formats = Serialization.formats(NoTypeHints)
val b = new ListBuffer[WOE]
val testMap = Map[String, String]()
testMap += ("1" -> "1.1")
b += WOE("1", immutable.Map(testMap.toList:_*))
b += WOE("3", immutable.Map(testMap.toList:_*))
println(write(b))
val js =
"""
[{"col":"1","woe":{"1":"1.1"}},{"col":"3","woe":{"1":"1.1"}}]
"""
val ab = parse(js).extract[List[WOE]]
println(ab.toString)
之前整理的一些方法
1、scala自带的Json解析
scala 2.10(以上,其他版本不清楚)自带Json解析,scala.util.parsing.json.JSON
object转json
val testMap = Map[String, String]()
testMap += ("1" -> "2.034")
testMap += ("2" -> "