3

我正在試圖將JsonPath的this example轉換爲Scala。它應該很容易與Java類似:對Java庫重載定義的模糊引用

List<String> authors = JsonPath.read(json, "$.store.book[*].author"); 

這我轉換到這個斯卡拉:

val authors = JsonPath.read(json, "$.store.book[*].author"); 

凡JSON是一個字符串。但我得到這個編譯錯誤。

ambiguous reference to overloaded definition, both method read in object JsonPath of type [T](x$1: String, 
x$2: String, x$3: <repeated...>[com.jayway.jsonpath.Filter[_]])T and method read in object JsonPath of type 
[T](x$1: Any, x$2: String, x$3: <repeated...>[com.jayway.jsonpath.Filter[_]])T match argument types 
(String,String) 

我以爲是關係到

public static <T> T read(Object json, String jsonPath, Filter... filters) 

public static <T> T read(String json, String jsonPath, Filter... filters) 

從com.jayway.jsonpath.JsonPath(0.9.1版本)。

如何消除此函數調用的歧義?

+0

看起來像* JsonPath *庫中的一個問題,因爲第一個參數中的字符串總是不明確的。 – MKaama

回答

3

對於這個特定的情況下,你可能只是做

JsonPath.read(json.asInstanceOf[Object], "$.store.book[*].author") 

這將只匹配的重載方法之一(其中一個需要Object)。推測該方法調用json.toString這是微不足道的,因爲我們已經有String

+0

有趣的是,我曾嘗試asInstanceOf [String]和asInstanceOf [java.lang.String]沒有任何運氣。 – user833970

+0

我試過這個改變。雖然編譯錯誤消失了,但是運行代碼導致在json中找不到鍵的錯誤: 在路徑$:com.jayway.jsonpath.PathNotFoundException com.jayway.jsonpath中未找到屬性['s3Bucket']。 PathNotFoundException:Property ['s3Bucket'] not found in path $ at com.jayway.jsonpath.internal.token.PropertyPathToken.evaluate(PropertyPathToken.java:41)........ –