在scala开发的工程中,可能需要用到json的相关知识。通常情况下,我们会用到JSON.toJSONString(...)和jsonObject.toJSONString(...)两种方法。使用这两种方法,需要添加阿里巴巴的fastjson的依赖
com.alibaba
fastjson
1.2.8
接下来,我们将通过实例看一下这两种方法所生成的json串有什么不同。
def jsontest(): Unit ={
var list:util.List[Any] = new util.ArrayList[Any]()
var map1 = new util.HashMap[String,Any]()
map1.put("name","Johnson")
map1.put("age",18)
map1.put("hobby","basketball")
var map2 = new util.HashMap[String,Any]()
map2.put("name","Jack")
map2.put("age",20)
map2.put("hobby","football")
var map3 = new util.HashMap[String,Any]()
map3.put("name","Johnson")
map3.put("age",22)
map3.put("hobby","swimming")
list.add(map1)
list.add(map2)
list.add(map3)
val jsonString = JSON.toJSONString(list, SerializerFeature.BeanToArray)
println(jsonString)
}
运行结果:
[{"name":"Johnson","age":18,"hobby":"basketball"},{"name":"Jack","age":20,"hobby":"football"},{"name":"Johnson","age":22,"hobby":"swimming"}]
def jsontest(): Unit ={
var list:util.List[Any] = new util.ArrayList[Any]()
var map1 = new util.HashMap[String,Any]()
map1.put("name","Johnson")
map1.put("age",18)
map1.put("hobby","basketball")
var map2 = new util.HashMap[String,Any]()
map2.put("name","Jack")
map2.put("age",20)
map2.put("hobby","football")
var map3 = new util.HashMap[String,Any]()
map3.put("name","Johnson")
map3.put("age",22)
map3.put("hobby","swimming")
list.add(map1)
list.add(map2)
list.add(map3)
val jsonObject = new JSONObject()
jsonObject.put("list",list)
val jsonString = jsonObject.toJSONString
println(jsonString)
}
运行结果:
{"list":[{"name":"Johnson","age":18,"hobby":"basketball"},{"name":"Jack","age":20,"hobby":"football"},{"name":"Johnson","age":22,"hobby":"swimming"}]}
从上面测试的结果,可以看出,方法二比方法一生成的json串多了一层“list”。
在方法一中,json串中是3个map对象;在方法二中,,json串中是一个list,list中包含了3个map对象。
注意:在使用方法一JSON.toJSONString()方法时,不能直接使用JSON.toJSONString(object),运行时会报方法重载的错误,toJSONString(x$1: Any)和toJSONString(x$1: Any, x$2: com.alibaba.fastjson.serializer.SerializerFeature*)同时匹配了方法的引用,导致报错。为了避免调用时存在方法重载的错误,在调用方法时,调用JSON.toJSONString(x$1: Any, x$2: com.alibaba.fastjson.serializer.SerializerFeature*),如上面方法一中的JSON.toJSONString(list, SerializerFeature.BeanToArray)