gpt4 book ai didi

scala - json4s 总是转义 unicode 字符 €

转载 作者:行者123 更新时间:2023-12-04 15:08:04 24 4
gpt4 key购买 nike

我尝试使用 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

最佳答案

详见 this github issue ,目前不可能使用 json4s native 来做到这一点。检查是否转义的代码是:

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

不满足这个条件。一种可能的解决方案(嗯,某种解决方案)是使用 jackson 而不是 native。然后这将起作用:

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

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

代码运行于 Scastie .

关于scala - json4s 总是转义 unicode 字符 €,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65706000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com