Pergunta

while trying my first steps with Scala/Spray i ran into a problem with proper handling of unicode in spray-json.

For example: á is resulting \u00e1 in json. The resulting header indicates UTF-8 as well as the proper setting auf -Dfile.encoding=UTF-8 which shows UTF-8 in the System.properties in Scala.

I found a possible solution here

But i am shamed to admit i have no clue how to implement this because i am not adressing the JsonPrinter directly. Here is what i have:

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))
    )

Simple Mapping in Person Class:

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 call within the routes:

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

So my question would be, how can i overwrite the printString Method within the JsonPrinter. I would appreciate any help. Thank you in advance!

Foi útil?

Solução

Spray uses the marshallers provided by the trait spray.httpx.PlayJsonSupport to marshall Play json values. Within that trait, it defines a marshaller for any type that has a Writes implicitly available in scope.

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

As you can see, at least in version 1.3.1, you can override how a JsValue is converted to a string by providing an implicit Function1[JsValue, String] in scope. For example, defining the following method in scope of your PersonJsonProtocol using the solution linked in your question as the implementation should give you the desired results.

implicit def noUnicodeEscPrettyPrinter(json: JsValue): String = NoUnicodeEscPrettyPrinter(json)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top