Get a specific parameter from a json string using

2019-05-31 09:51发布

I have a json string and I want to extract a parameter from this json using JsonPath in scala. Given 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"
        }
}

I tried to use the below code to get the parameter event_type as found in some examples but it throws an error:

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

Error:

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");

Can someone please tell me what am I missing here?

1条回答
再贱就再见
2楼-- · 2019-05-31 10:29

You need to give a hint to the Scala compiler so that it is able to select the right method:

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

Here is the complete test app:

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
}
查看更多
登录 后发表回答