clojure - 如何将 Java 字符串转换为 EDN 对象?
问题描述
在 Clojure 中,我使用 cheshire ( https://github.com/dakrone/cheshire ) 库的“生成字符串”函数将 EDN 转换为 JSON。
如果我直接使用 Clojure 中的 EDN 数据调用它,它工作正常,即
(defn generate-json-string
(generate-string {:foo "bar" :baz {:eggplant [1 2 3]} :sesion nil} {:pretty true})
)
Output =>
{
"foo": "bar",
"baz": {
"eggplant": [1,2,3]
},
"sesion": null
}
但是如果我从 Java 调用上面的函数并以 Java 字符串的形式将上面的相同内容传递给它,它就行不通了
(defn generate-json-string [content]
(generate-string content {:pretty true})
)
Output =>
"{:foo \"bar\" :baz {:eggplant [1 2 3]} :session nil}"
我怎样才能解决这个问题?
解决方案
下面显示了如何将数据读/写到 JSON 字符串或 EDN 字符串中。
请注意,JSON 和 EDN 都是字符串序列化格式,尽管 Clojure 文字数据结构通常(草率地)称为“EDN 数据”,即使 EDN 在技术上意味着字符串表示。
另外,请注意clojure.tools.reader.edn是将 EDN 字符串转换为 Clojure 数据结构的最佳(最安全)方法。
(ns tst.demo.core
(:use tupelo.core tupelo.test)
(:require
[clojure.tools.reader.edn :as edn]
[tupelo.core :as t]
[tupelo.string :as ts] ))
(def data
"A clojure data literal"
{:a "hello" :b {:c [1 2 3]}})
(dotest
(let [json-str (t/edn->json data) ; shortcut to Cheshire
from-json (t/json->edn json-str) ; shortcut to Cheshire
edn-str (pr-str data) ; convert Clojure data structure => EDN string
; Using clojure.tools.reader.edn is the newest & safest way to
; read in an EDN string => data structure
from-edn (edn/read-string edn-str)]
; Convert all double-quotes to single-quotes for ease of comparison
; with string literal (no escapes needed)
(is= (ts/quotes->single json-str) "{'a':'hello','b':{'c':[1,2,3]}}")
(is= (ts/quotes->single edn-str) "{:a 'hello', :b {:c [1 2 3]}}")
; If we don't convert to single quotes, we get a messier escaped
; string literals with escape chars '\'
(is-nonblank= json-str "{\"a\":\"hello\",\"b\":{\"c\":[1,2,3]}}")
(is-nonblank= edn-str "{:a \"hello\", :b {:c [1 2 3]}}")
; Converting either EDN or JSON string into clojure data yields the same result
(is= data
from-json
from-edn)))
推荐阅读
- android-studio - 从 Android 应用程序连接到 MariaDB
- html - 我在我的网站上使用引导导航栏,与其他页面相比,它在索引页面上的作用不同
- java - 集成测试无法连接,使用 SpringBoot/Jsoup 集成测试的 Java RESTful Web 服务手动浏览器测试成功
- javascript - React - 在组件内部使用“文档”
- xpath - XQuery 解码 HTTP 请求 - 无法解析查询
- html - 在具有灵活行的嵌套网格布局中,为什么滚动条需要两个“溢出:自动”
- python - 相关网络的前向传递输出在没有反向传播的情况下发生变化
- vba - 文件不移动 VBA
- tensorflow - 使用机器学习检测 CANBUS 模式
- tensorflow - TensorFlow 中的回调