gschjetne / json-mop

A metaclass for bridging CLOS and JSON objects
MIT License
61 stars 9 forks source link

Support json-type (:hash-table object) #11

Closed riktam closed 1 year ago

riktam commented 1 year ago

Allow json-type of (:hash-table object)

kilianmh commented 1 year ago

For a project of mine, I developed a bit more advanced solution where you can specify the hash-table key-type as well: (:hash-table key-type value-type). E.g. (:hash-table :string :number), or (:hash-table :any object)

This is my version:

(defmethod to-lisp-value ((value hash-table) (json-type cons))
  (destructuring-bind (type key-type value-type)
      json-type
    (ecase type
      (:hash-table
       (let ((hash-table
               (make-hash-table :size (hash-table-size value)
                                :test (case key-type
                                        ((:string :any)
                                         (function equal))
                                        (otherwise
                                         (function eql))))))
         (maphash #'(lambda (key value)
                      (setf (gethash (to-lisp-value key
                                                    key-type)
                                     hash-table)
                            (to-lisp-value value
                                           value-type)))
                  value)
         hash-table)))))
riktam commented 1 year ago

Are you sure that the "spec" allows for keys other than strings? I'm ok with with either implementation. My case only had string keys.

kilianmh commented 1 year ago

Actually you're right: keys in JSON Objects can only be strings. So your version is superior.

gschjetne commented 1 year ago

This looks good to me, but would you consider adding a unit test?

riktam commented 1 year ago

Added decoding, tests and updated the documentation.

kilianmh commented 1 year ago

You should probably squash the changes into one commit and rebase on master.

riktam commented 1 year ago

Done