播放 json:将 json 值解析为不带引号的字符串

Play json: parse json value to string without quotes

我有一个 json 对象可以说

{
    "company":"77160"
}

我在 Scala 中用 play.api.libs.json 解析它,如下所示:

cols = Json.parse(line).as[JsObject]
val company = s"${cols("company")}".toString

但返回的字符串有双引号(即“”77160“”) 是什么赋予了?如何在不自己重新解析的情况下获得普通字符串((即“77160”))(例如使用替换功能)。

您必须在 cols("company") 上致电 .as[String]。参见 https://www.playframework.com/documentation/2.8.x/ScalaJson#Using-JsValue.as/asOpt

像这样:

cols = Json.parse(line).as[JsObject]
val company = cols("company").as[String]

如果您想知道幕后发生了什么,as 方法属于 JsValue.as[T](implicit fjs: Reads[T]): T 类型,它使用隐式查找 T 的隐式转换器。由于我们在这里使用 as[String],它将搜索适合该类型的隐式转换器,并且由于 play 已经在其 library 中定义了它,它将使用该转换器。