当然(bean javaObject)
(请参阅bean ClojureDoc)效果很好,但它不允许您选择所需的属性和不想要的属性。当您将结果映射输入到json-str
函数中时,它会产生影响,在这种情况下,您可能会收到一条错误消息:“不知道如何编写 JSON of ...”
当我处理基本上接受 JSON(如 neocons 的底层)的 NoSQL DB(mongoDB、neo4j)时,我发现这很烦人。
那么我的解决方案是什么?
(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)
希望这会帮助某人...