1
我有使用噴霧框架,看起來像以下書面一塊API的Scalatest:噴霧試驗情況下不屬性解組UTF-8編碼的使用JSON HTTPEntity
"correctly deserializes multi-lang title metadata" in {
implicit def json4sFormats: org.json4s.Formats = ModelJsonHelper.jsonFormats
val v2MultiLangTitle = getStringFromResource("/json_samples/cmp.asset.v2.AssetWriteMultiMetadata.json")
//Deserialize
val v2AssetEither = HttpEntity(`application/cmp.ela.assetWrite.v2+json`, v2MultiLangTitle).as[Asset]
v2AssetEither.isRight shouldEqual true
v2AssetEither.right.map(asset => {
asset.assetMetadata.getOrElse(List()).size shouldEqual(3)
asset.assetMetadata.getOrElse(List())(1).language shouldEqual("es")
asset.assetMetadata.getOrElse(List())(1).data.title shouldEqual(Some("Encabezado prueba de AFP"))
asset.assetMetadata.getOrElse(List())(2).language shouldEqual("tlh")
asset.assetMetadata.getOrElse(List())(2).data.title shouldEqual(Some("Daj jaw AFP"))
asset.assetMetadata.getOrElse(List())(0).language shouldEqual("de")
asset.assetMetadata.getOrElse(List())(0).data.title shouldEqual(Some("Test AFP Überschrift"))
})
}
def getStringFromResource(input: String): String = {
Source.fromInputStream(this.getClass.getResourceAsStream(input))(Codec.UTF8).getLines.mkString("")
}
正在處理的JSON是以下
{
"assetMetadata" : [
{
"title": "Test AFP Überschrift",
"language": "de"
},
{
"title": "Encabezado prueba de AFP",
"language": "es"
},
{
"title": "Daj jaw AFP",
"language": "tlh"
}
]
}
,故障發生在德國元音:
[info] - correctly deserializes multi-lang title metadata *** FAILED ***
[info] Some("Test AFP �berschrift") did not equal "Test AFP Überschrift" (V2AssetWriteMarshallerSpec.scala:367)
在表面下,有一些json4s用於解包過程。但是,如果我直接使用json4s解析器,德國字符正確處理:
import scala.io.Source
import java.io.FileInputStream
val v = Source.fromInputStream(new FileInputStream("/path/to/project/src/test/resources/json_samples/cmp.asset.v2.AssetWriteMultiMetadata.json")).getLines.mkString("")
import org.json4s._
import org.json4s.native.JsonMethods._
val obj = parse(v)
(obj \ "assetMetadata")
給我的結果:
res0: org.json4s.JValue = JArray(List(JObject(List((title,JString(Test AFP Überschrift)), ....
我在噴霧1.3.3和3.2.10 json4s。在HttpEntity
該類型的自定義類型,我已經嘗試添加("charset" -> "UTF-8")
作爲一個參數,像這樣:
val `application/cmp.ela.assetWrite.v2+json` = register(
MediaType.custom(
mainType = "application",
subType = "cmp.ela.assetWrite.v2+json",
compressible = true,
binary = false,
parameters = Map[String,String]("charset" -> "UTF-8")
)
)
..但是測試還是失敗的無效字符。我如何讓Spray正確解開一個包含國際字符的字符串?