scala-使用map函数连接JValue

时间:2018-08-07 16:21:12

标签: json scala function json4s

我最近开始使用Scala,并且可能缺少有关map函数的某些信息。我知道,它会返回通过应用给定函数得到的新值。

例如,我有一个JValues数组,想要将该数组中的每个值与另一个JValue连接起来,或者只是将其转换为String,如下例所示。

val salesArray = salesJValue.asInstanceOf[JArray]
val storesWithSales = salesArray.map(sale => compact(render(sale)) //Type mismatch here
val storesWithSales = salesArray.map(sale => compact(render(sale) + compact(render(anotherJvalue))) //Type mismatch here

如我所见,存在类型不匹配的情况,因为实际值是String,预期值为JValue。即使我compact(render(sale).asInstanceOf[JValue]也不允许将字符串强制转换为JValue。是否可以从地图函数返回其他类型?我如何处理数组值以将每个数组值转换为另一种类型?

1 个答案:

答案 0 :(得分:3)

看看map方法的类型签名:

def map(f: JValue => JValue): JValue

因此,它与其他map方法有点不同,因为您必须指定返回类型为JValue的函数。这是因为JArray专门表示反序列化的JSON树,并且不能仅包含JValue来保存任意对象或数据。

如果要处理JArray的每个值,请先对其调用.children。这样就为您提供了一个List[JValue],然后有一个更通用的map方法,因为List可以容纳任何类型。其类型签名为:

def map[B](f: A => B): List[B]

因此您可以这样做:

val storesWithSales = salesArray.children.map(sale => compact(render(sale)))