我正在使用Liberator,我很难将我的POSTed数据放入一个以关键字为关键字的地图中。以下是我的参考资料,以及一些用于测试的打印行:
(defresource finish_validation
:allowed-methods [:post]
:available-media-types ["application/json"]
:post! (fn [context]
(let [params (slurp (get-in context [:request :body]))
mapped_params (cheshire/parse-string params)]
(println (type params))
(println (type mapped_params))
(validation/finish mapped_params)))
:handle-created (println ))为了进行测试,我使用curl发布数据:
curl -H "Content-Type: application/json" -X POST -d '{"email":"test@foo.com","code":"xyz"}' http://localhost:8080/validatecheshire将参数转换为映射,但键不是关键字:我得到{email test@foo.com, code xyz}作为输出,而不是期望的{:email test@foo.com, :code xyz}。
我应该做一些不同的事情吗?这是获取数据的正确方法吗?
发布于 2015-04-18 08:33:51
您需要利用ring的wrap-params中间件,再加上将参数映射转换为键映射的wrap-keyword-params中间件。
(ns your.namespace
(:require [ring.middleware.params :refer [wrap-params]]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]))
(def app
(-> some-other-middleware
wrap-keyword-params
wrap-params))将此中间件与wrap-params结合使用,可以将参数转换为使用密钥。添加此中间件后,您可以从请求映射中访问您的参数,如(-> ctx :request :params)。不需要在每次请求时转换它们。这将处理所有请求。
发布于 2015-04-16 08:53:24
我只需要在调用cheshire函数的末尾加上"true“,键就会作为关键字返回:
(cheshire/parse-string params true)发布于 2015-04-17 10:13:41
根据您的需求,您可以使用各种环中间件来简化post数据的处理。这将允许您在一个地方处理您的json数据,并消除在每个处理程序/资源定义中进行重复数据处理的需要。有几种方法可以做到这一点。您可以将json数据作为关键字参数添加到params映射或json-params映射中。看看ring.middleware.format和ring.middleware.json吧。
https://stackoverflow.com/questions/29663217
复制相似问题