[英]How to convert Java String to EDN object?
在 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 String 的形式將上面的相同內容傳遞給它,它就行不通了
(defn generate-json-string [content]
(generate-string content {:pretty true})
)
Output =>
"{:foo \"bar\" :baz {:eggplant [1 2 3]} :session nil}"
我怎樣才能解決這個問題?
我能夠通過使用 edn/read-string 函數來解決這個問題。
(defn generate-json-string [content]
(generate-string (edn/read-string content) {:pretty true})
)
下面顯示了如何將數據讀/寫到 JSON 字符串或 EDN 字符串中。
請注意,JSON 和 EDN 都是字符串序列化格式,盡管 Clojure 文字數據結構通常(草率地)僅稱為“EDN”的“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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.