简体   繁体   中英

How can I use clojure.core/bean recursively?

So I think clojure.core/bean is pretty close to what I want, but I'm working with a Java application that has nested beans, such that I end up with maps like this:

{:month-total 3835.0 :name "Jan's Meat Diner" :owners #<BarOwner[] [Lcom.fancypants.BarOwner;@1fb332d}

How, do I call bean recursively on a Java object so that I can get my imaginary BarOwner object to emit itself as a map, too:

{:month-total 3835.0 :name "Jan's Meat Diner" :owners { [:name "Jack"] [:name "Jill"] } }

Edit 1

I have found that clojure/java.data and from-java is probably a better fit for this kind of thing than bean .

Although it's probably not an ideal answer to "how to use bean recursively", using more of the richer contrib libraries under the Clojure community's site did solve it. Specifically

clojure/java.data

provides simple recursive bean resolving, and can be configured to handle java types specifically in the hairy cases. I'd recommend this to other people who want to use bean .

It is very tricky to find out what is a bean and what is not. This seems to do the trick for beans inside beans and properties that are lists. Probably you will want to add more classes to the probably-bean? function and perhaps some support for properties that are maps.

(defn probably-bean? [o]
   (and (not (coll? o))
         ((complement #{Class Long String clojure.lang.Keyword}) (class o))))

(defn transf [o]
    (cond
            (instance? java.util.List o) (into [] (map transf o))
            (probably-bean? o) (into {} (seq (bean o)))
            :else o))

(defn to-bean [o]
    (clojure.walk/prewalk #(transf %) o))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM