2014-02-17 26 views
1

當我嘗試使用Scala/Spray的第一步時,遇到了一個問題,正確處理了噴碼json中的unicode。在Spray-json中處理Unicode,並重寫JsonPrinter

例如:á是在json中生成的。生成的頭文件指示UTF-8以及適當的設置auf -Dfile.encoding = UTF-8,它在Scala的System.properties中顯示UTF-8。

我發現了一個可能的解決方案here

但我羞愧地承認我不知道如何實現這一點,因爲我並沒有直接adressing的JsonPrinter。 這裏是我有:

JsonProtocol:

object PersonJsonProtocol extends DefaultJsonProtocol { 
    implicit object PersonJsonFormat extends RootJsonFormat[Person] { 
    def write(per: Person) = JsObject(
     "name" -> JsString(per.name), 
     "surname" -> JsString(per.surname), 
     "addresses" -> JsArray(per.addresses.toList.map(_.toJson)) 
    ) 

簡單映射在Person類:路線內

val simple = { 
    get[String]("person_code") ~ 
    get[String]("name") ~ 
    get[String]("surname") map { 
    case person_code~name~surname => 
    new Person(person_code, name, surname, adressDao.findAll(person_code)) 
    } 
    } 

DB電話:

ctx: RequestContext => ctx.complete(StatusCodes.OK, personDAO.findAll()) 

所以我的問題是,我怎麼能覆蓋JsonPrinter中的printString方法。 我將不勝感激任何幫助。先謝謝你!

+0

對於後人來說,這是spray-json中的相關問題,需要解決https://github.com/spray/spray-json/issues/46。 –

+0

@DaveSwartz謝謝。所以唯一的辦法似乎是找到一個非官方的解決方法。 – Klink

回答

0

Spray使用特質spray.httpx.PlayJsonSupport提供的marshallers來蒐集json值。在該特徵中,它定義了一個編組器,該編組器可以在範圍內隱式提供Writes

implicit def playJsonMarshaller[T: Writes](implicit printer: JsValue => String = Json.stringify) = ??? 

正如你所看到的,至少在1.3.1版本中,您可以覆蓋JsValue是如何通過提供範圍隱式Function1[JsValue, String]轉換爲字符串。例如,在您的PersonJsonProtocol範圍內使用您的問題中鏈接的解決方案定義以下方法作爲實現應該會給您預期的結果。

implicit def noUnicodeEscPrettyPrinter(json: JsValue): String = NoUnicodeEscPrettyPrinter(json)