在Scala中将JSON字符串转换为JSON对象 [英] Converting JSON string to a JSON object in Scala

查看:1972
本文介绍了在Scala中将JSON字符串转换为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将简单的JSON字符串(例如{"Name":"abc", "age":10})转换为相应的JSON对象(而不是自定义的Scala对象,例如"Person"). Scala是否支持任何将String转换为JSON对象的内置方法?

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"). Does Scala support any in-built methods to convert a String to a JSON object?

我不会进行任何复杂的JSON操作.我只需要将String转换为JSON对象.最简单的方法是什么?我是Scala的新手,所以如果这个问题听起来很基础,我深表歉意.

I'm not going to have any complex JSON operations. I just need to convert the String to a JSON object. What is the simplest way to do this? I'm new to Scala, so I apologize if this question sounds very basic.

谢谢.

推荐答案

注意:从技术上讲,不再存在解析JSON的Scala本机"核心方法.您应该使用外部支持的库,例如Spray JSON或Play JSON.

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.

从Scala 2.11开始,解析器组合库不再包含在核心语言jar中,需要单独添加到您的项目中.此外,此后在解析器组合器库的社区支持版本中不推荐使用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.

如果愿意,您仍然可以将其添加到您的项目中,方法是将以下内容添加到build.sbt中:

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"

您可以在 https://github.com/scala上找到该库的源代码. /scala-parser-combinators .

由于您专门询问了Scala的JSON解析本机功能,因此您正在寻找的包是scala.utils.parsing.json.像下面这样的东西应该起作用:

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将采用以下值:Some(Map(Name -> abc, age -> 10.0))

这篇关于在Scala中将JSON字符串转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆