当前位置: 首页 > 工具软件 > Scala JSON > 使用案例 >

scala json处理入门

隗星驰
2023-12-01

依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

构建json对象

def test1(): Unit ={
  val nObject = new JSONObject()
  nObject.put("name","xiaoming")
  nObject.put("age",23)
  println(nObject)//{"name":"xiaoming","age":23}
}

json字符串转json对象

def decode(): Unit = {
    val str = "{'name':'xiaoming','age':23}"
    val nObject: JSONObject = JSON.parseObject(str)
    val str1: String = nObject.getString("name")
    println(s"str1 = ${str1}")//str1 = xiaoming
  }

Json对象转字符串

 def json2str(): Unit = {
    val str = "{'name':'xiaoming','age':23}"
    val nObject: JSONObject = JSON.parseObject(str)
    val string: String = nObject.toJSONString
    println(s"string = ${string}")//string = {"name":"xiaoming","age":23}
  }

提取json字符串中数组的部分信息

 def getarray(): Unit ={
    import com.alibaba.fastjson.JSONArray
    import com.alibaba.fastjson.JSONObject
    val str: String = "{\n" + "'name':'网站',\n" + "'num':3,\n" + "'sites':[ 'Google', 'Runoob', 'Taobao' ]\n" + "}"
    //字符串转json对象
    val jsonObject: JSONObject = JSON.parseObject(str)
    //将JSON对象转化为字符串
    val sites: String = jsonObject.getString("sites")
    //提取字符串中的数组
    val array: JSONArray = JSON.parseArray(sites)
    //获取数组的第一个元素
    System.out.println(array.get(0)) //Google
  }

参考

Java 中 JSON 的使用 | 菜鸟教程

 类似资料: