首页 > 解决方案 > 如何将 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}"

我怎样才能解决这个问题?

标签: clojureclojure-java-interopedncheshire

解决方案


下面显示了如何将数据读/写到 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)))

推荐阅读