Search code examples
clojureclojure-java-interop

Clojure use Java JsonPath


I am trying to use https://github.com/json-path/JsonPath in Clojure

It looks straightforward from the README, especially since it uses static functions. So I replicated the example from the README:

(import '[com.jayway.jsonpath JsonPath Criteria Filter])


(JsonPath/parse "{\"a\":\"1\"}") ;; returns a com.jayway.jsonpath.internal.JsonContext

(JsonPath/read (JsonPath/parse "{\"a\":\"1\"}") "$.a")
;; (.read (JsonPath/parse "{\"a\":\"1\"}") "$.a")
;; Exception ->
;; 1. Caused by java.lang.IllegalArgumentException
;; No matching method: read
;; I tried variations of the above line
;; for some reason this seems to want to take `this` as first parameter - I cannot
;; figure out why, and cannot seem to be able to pass a valid value

How can I call this Java static function from Clojure? Why does it want as this?

dependency: [com.jayway.jsonpath/json-path "2.4.0"]


Solution

  • The problem is the varargs with Predicate on read. On JVM-Level you have to pass those args as array. With Java the compiler will take care of that.

    E.g. this works:

    user=> (import '[com.jayway.jsonpath JsonPath Criteria Filter Predicate])
    #<Class@5a114a96 com.jayway.jsonpath.Predicate>
    user=> (JsonPath/read "{\"a\":\"1\"}" "$.a" (into-array Predicate []))
    "1"