当前位置: 首页 > 工具软件 > scala0.json > 使用案例 >

Scala中Json数据解析(net.minidev.json)

越景天
2023-12-01

解析json字符串中的类型对应如下:

json格式scala格式
整数java.lang.Integer
StringString
dictJSONObject
listJSONArray

测试代码如下:

import net.minidev.json.parser.JSONParser
import net.minidev.json.{JSONArray, JSONObject}
import scala.collection.JavaConversions._
    
object TestScala {
  def main(args: Array[String]): Unit = {

    var jsonParser = new JSONParser()
    var jsonData = jsonParser.parse("""{"_record_id":"00001", "inte": 100, "dicts": {"key1": "value1"},"lists": ["1", "2"]}""").asInstanceOf[JSONObject]
    for(key <- jsonData.keySet()){
      println("key:" + key + "\tkey_class:" + key.getClass + "\tvalue:" + jsonData.get(key) + "\tvalue_class:" + jsonData.get(key).getClass)
    }
    jsonData.put("new_integer", new Integer(10))
    println(jsonData)
        jsonData.put("new_integer", new Integer(10))
    val json = new JSONArray()
    json.add("province")
    json.add("province2")

    jsonData.put("test_list", json)

    val jsonO = new JSONObject
    jsonO.put("als", "res")
    jsonData.put("info", jsonO)

    if(jsonData.getOrElse("inte","").toString == "100"){
      println(jsonData.getOrElse("inte","").getClass)
    }

    println("inte: " + jsonData.getOrElse("inte", new Integer(99999)).asInstanceOf[Integer])
    println("new: "+ jsonData.getOrElse("new", new Integer(99999)).asInstanceOf[Integer])
    println(jsonData)
  }
}

得到结果为:

key:_record_id	key_class:class java.lang.String	value:00001	value_class:class java.lang.String
key:lists	key_class:class java.lang.String	value:["1","2"]	value_class:class net.minidev.json.JSONArray
key:inte	key_class:class java.lang.String	value:100	value_class:class java.lang.Integer
key:dicts	key_class:class java.lang.String	value:{"key1":"value1"}	value_class:class net.minidev.json.JSONObject
{"_record_id":"00001","lists":["1","2"],"inte":100,"new_integer":10,"dicts":{"key1":"value1"}}
class java.lang.Integer
inte: 100
new: 99999
{"_record_id":"00001","lists":["1","2"],"inte":100,"new_integer":10,"test_list":["province","province2"],"dicts":{"key1":"value1"},"info":{"als":"res"}}

 类似资料: