scala使用Gson和FastJson解析JSON

Maven依赖:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.51</version>
</dependency>

fastjson:

import com.alibaba.fastjson._
import scala.collection.JavaConversions._
object TestFastJson {
def main (args: Array[String]): Unit ={

println("fastJson tests....")
var badJsonStr="{\"employees\":\"{\"firstName\":\"三\",\"lastName\":\"张\"}\"}"
try{
  var badJsonObject=JSON.parseObject(badJsonStr)
}
catch{
  //json格式不正确,报错
  case e:Exception=>println(e.getMessage)
}
/*测试JsonObject*/
var jsonObjectStr="{\"firstName\":\"三\" , \"lastName\":\"张\"}"
var jsonObject:JSONObject=JSON.parseObject(jsonObjectStr)
println("firstName="+jsonObject.getString("firstName")+",lastName="+jsonObject.getString("lastName"))
/*测试JsonArray*/
var jsonArrayStr="[{\"firstName\":\"三\",\"lastName\":\"张\"},{\"firstName\":\"四\",\"lastName\":\"李\"}]"
//生成JsonArray对象
var jsonArray:JSONArray=JSON.parseArray(jsonArrayStr)
//遍历JsonArray
jsonArray.foreach(ja=>{
  //scala不能推断出ja是JsonObject,只能手动转成JsonObject
 var json=JSON.parseObject(ja.toString)
  //输出
  println("firstName="+json.getString("firstName")+",lastName="+json.getString("lastName"))
})

}
}

--gson

import com.google.gson._
import scala.collection.JavaConversions._
/**

  • Created by Administrator on 2018/10/21.

*/
object TestGson {
def main(args: Array[String]) {

println("gson tests....")
var badJsonStr="{\"employees\":\"{\"firstName\":\"三\",\"lastName\":\"张\"}\"}"
try{
  var badJsonObject=new JsonParser().parse(badJsonStr).getAsJsonObject
}
catch{
  //json格式不正确,报错
  case e:Exception=>println(e.getMessage)
}
/*测试JsonObject*/
var jsonObjectStr="{\"firstName\":\"三\" , \"lastName\":\"张\"}"
var jsonObject=new JsonParser().parse(jsonObjectStr).getAsJsonObject
println("firstName="+jsonObject.get("firstName").getAsString+",lastName="+jsonObject.get("lastName").getAsString)
/*测试JsonArray*/
var jsonArrayStr="[{\"firstName\":\"三\",\"lastName\":\"张\"},{\"firstName\":\"四\",\"lastName\":\"李\"}]"
//生成JsonArray对象
var jsonArray=new JsonParser().parse(jsonArrayStr).getAsJsonArray
//遍历JsonArray
jsonArray.foreach(ja=>{
  //scala可以识别ja是JsonObject,可以直接进行解析          println("firstName="+jsonObject.get("firstName").getAsString+",lastName="+jsonObject.get("lastName").getAsString)
})

}
}

上一篇:一步一步学Ruby(十五):错误处理和异常


下一篇:MySQL 传统复制中常见故障处理和结构优化案例分析