Scala解析Json字符串

1. 添加相应依赖

       Json解析工具使用的 json-smart,曾经对比过Java的fastjson、gson。Scala的json4s、lift-json。其中 json-smart 解析速度是最快的。java

<dependency>
            <groupId>net.minidev</groupId>
            <artifactId>json-smart</artifactId>
            <version>2.3</version>
        </dependency>

2. Scala代码

package Test

import java.util

import net.minidev.json.JSONObject
import net.minidev.json.parser.JSONParser

import scala.collection.JavaConversions._
import scala.collection.mutable
import scala.util.parsing.json.JSON

/** * Created by zhanghuayan on 2017/3/30. */
object Test {
  def main(args: Array[String]): Unit = {

    val str2 = "{\"name\":\"jeemy\",\"age\":25,\"phone\":\"18810919225\"}"
    val jsonParser = new JSONParser()

    val jsonObj: JSONObject = jsonParser.parse(str2).asInstanceOf[JSONObject]
    val name = jsonObj.get("name").toString
    println(name)

    val jsonKey = jsonObj.keySet()
    val iter = jsonKey.iterator

    while (iter.hasNext) {
      val instance = iter.next()
      val value = jsonObj.get(instance).toString
      println("key: " + instance + " value:" + value)
    }

  }
}



对机器学习,人工智能感兴趣的小伙伴,请关注个人公众号:
web

这里写图片描述