使用Scala中的JsonPath从json字符串获取特定参数 [英] Get a specific parameter from a json string using JsonPath in scala
本文介绍了使用Scala中的JsonPath从json字符串获取特定参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个json字符串,我想在scala中使用JsonPath从此json提取参数. 鉴于杰森:
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"
}
}
我尝试使用下面的代码来获取某些示例中找到的参数event_type,但它会引发错误:
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: 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?
推荐答案
您需要给Scala编译器一个提示,以便它能够选择正确的方法:
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
}
这篇关于使用Scala中的JsonPath从json字符串获取特定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文