使用scala中的JsonPath从json字符串中获取特定参数

时间:2018-01-03 21:36:22

标签: scala jsonpath

我有一个json字符串,我想在scala中使用JsonPath从这个json中提取一个参数。 鉴于Json:

{
    "message_payload":"6b700b000006",
    "message_encryption_version":"2.0",
    "message_version":"1.0",
    "message_metadata":{
        "marketplace_id":"1",
        "workflow_id":"5906bd4e-52eb-4e2d-9a16-034fb67572f1",
        "hostname":"dev-dsk-shivabo-2b-3c0a1bd6.us-west-2.amazon.com",
        "event_type":"MerchantRegistrationFraudEvaluation",
        "event_date":"1513665186657"
        }
}

我尝试使用以下代码获取参数event_type,如某些示例中所示,但它会引发错误:

val eventType = JsonPath.read(jsonString, "$.message_metadata.event_type")

错误:

error: ambiguous reference to overloaded definition,
[scalac-2.11] both method read in object JsonPath of type [T](x$1: String, x$2: String, x$3: com.jayway.jsonpath.Predicate*)T
[scalac-2.11] and  method read in object JsonPath of type [T](x$1: Any, x$2: String, x$3: com.jayway.jsonpath.Predicate*)T
[scalac-2.11] match argument types (String,String)
[scalac-2.11]     val eventType = JsonPath.read(jsonString, "$.message_metadata.event_type");

有人可以告诉我在这里缺少什么吗?

1 个答案:

答案 0 :(得分:3)

您需要提示Scala编译器,以便能够选择正确的方法:

val eventType = JsonPath.read[String](jsonString, "$.message_metadata.event_type")

以下是完整的测试应用:

import com.jayway.jsonpath.JsonPath

object TestApp extends App {
  val jsonString =
    """{
      |    "message_payload":"6b700b000006",
      |    "message_encryption_version":"2.0",
      |    "message_version":"1.0",
      |    "message_metadata":{
      |        "marketplace_id":"1",
      |        "workflow_id":"5906bd4e-52eb-4e2d-9a16-034fb67572f1",
      |        "hostname":"dev-dsk-shivabo-2b-3c0a1bd6.us-west-2.amazon.com",
      |        "event_type":"MerchantRegistrationFraudEvaluation",
      |        "event_date":"1513665186657"
      |        }
      |}""".stripMargin


  val eventType = JsonPath.read[String](jsonString, "$.message_metadata.event_type")
  println(eventType)  // MerchantRegistrationFraudEvaluation
}