Converting JSON string to a JSON object in Scala

后端 未结 4 907
生来不讨喜
生来不讨喜 2020-12-31 04:07

I want to convert a simple JSON string such as {\"Name\":\"abc\", \"age\":10} to the corresponding JSON object (not a custom Scala object such as \"Person\"). D

4条回答
  •  一向
    一向 (楼主)
    2020-12-31 04:24

    Note: Technically, there is no longer a core Scala "native" way of parsing JSON. You should use an external, supported library like Spray JSON or Play JSON.

    As of Scala 2.11 the parser-combinator library is no longer included in the core language jar and needs to be added separately to your project. Further, the JSON parser has since been deprecated in the community supported version of the parser-combinator library. I would not recommend using this library.

    You can still add it to your project, if you choose to, by adding the following to your build.sbt:

    libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.4"

    You can find the source code for the library at https://github.com/scala/scala-parser-combinators.


    Since you asked specifically about Scala's native facilities for JSON parsing – the package you are looking for is the scala.utils.parsing.json. Something like the following should work:

    import scala.util.parsing.json._
    
    val parsed = JSON.parseFull("""{"Name":"abc", "age":10}""")
    

    parsed will take on the value: Some(Map(Name -> abc, age -> 10.0))

提交回复
热议问题