【问题标题】:json4s always escapes unicode character €json4s 总是转义 unicode 字符 €
【发布时间】:2021-01-13 16:30:29
【问题描述】:

我尝试用 json4s 漂亮地编写一个包含€ 字符的JString,如下所示:

import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.native.Serialization.writePretty
import org.json4s.{DateFormat, DefaultFormats, Formats, JString}

import java.util.{Date, TimeZone}

object Json4sEncodingTest {

  val formats = new Formats {

    val dateFormat: DateFormat = new DateFormat {
      override def parse(s: String): Option[Date] =
        try {
          Option(
            DateTime
              .parse(s, ISODateTimeFormat.dateTimeParser().withZoneUTC())
              .withZone(DateTimeZone.forID(timezone.getID))
              .toDate
          )
        } catch {
          case e: IllegalArgumentException => None
        }
      override def format(d: Date): String = DefaultFormats.lossless.dateFormat.format(d)
      override def timezone: TimeZone = DefaultFormats.lossless.dateFormat.timezone
    }

    override def alwaysEscapeUnicode: Boolean = false
  }

  def main(args: Array[String]): Unit = {
    println(writePretty(JString("2€"))(formats))
  }

}

这会导致:

"2\u20ac"

我的预期结果是:

"2€"

我发现在 org.json4s.ParserUtil.quote 中 \u2000 和 \u2100 之间的字符总是被转义。

问题:为什么会这样?

  • json4s版本:3.7.0-M7
  • scala 版本:2.12.11

【问题讨论】:

标签: scala escaping json4s


【解决方案1】:

正如this github issue 中所述,目前使用 json4s native 是不可能做到这一点的。检查是否逃逸的代码是:

(c >= '\u0000' && c <= '\u001f') || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')

而€ 不满足此条件。一种可能的解决方案(嗯,一种解决方案)是使用杰克逊而不是本机。然后这将起作用:

import org.json4s.jackson.JsonMethods._
import org.json4s.JsonAST.JString

println(pretty(render(JString("2€"))))

代码在Scastie 运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    相关资源
    最近更新 更多