当然,(参见bean ClojureDoc)工作得很好,但它不让你选择你想要的属性和你不想要的属性。当您将生成的映射输入到函数中时,它会产生影响,在这种情况下,您可能会收到一个错误:“不知道如何编写以下 JSON:(bean javaObject)
json-str
当我处理NoSQL DB(mongoDB,neo4j)时,我发现这很烦人,它基本上接受JSON(就像neocons的基础一样)。
那么我的解决方案是什么呢?
(defmacro get-map-from-object-props [object & props]
;->> will eval and reorder the next list starting from the end
(->> (identity props) ;identity is here to return the 'props' seq
;map each property with their name as key and the java object invocation as the value
;the ~@ is here to unsplice the few properties
(map (fn [prop] [(keyword (str prop)) `(.. ~object ~@(prop-symbol prop) )]))
(into {})))
;getter is a simple function that transform a property name to its getter "name" -> "getName"
(defn prop-symbol [prop]
(map symbol (map getter (clojure.string/split (str prop) #"\\."))))
你可以这样使用它(是的,该函数会处理一连串的属性(如果有的话)
(get-map-from-object-props javaObject property1 property2 property3.property1)
希望能帮助别人...