Get a specific parameter from a json string using JsonPath in scala

六眼飞鱼酱① 提交于 2019-12-22 18:42:34

问题


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:


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
}


来源:https://stackoverflow.com/questions/48085463/get-a-specific-parameter-from-a-json-string-using-jsonpath-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!