How to add a custom marshaller to akka http? How to add a custom marshaller to akka http? json json

How to add a custom marshaller to akka http?


From what I understand, you have all the pieces, you just need to put them together.

Spray json provides support for marshalling common types, such as Int, String, Boolean, List, Map, etc. But it doesn't know how to marshall 'Currency'. And to solve that you have created a custom marshaller for 'Currency' objects. You just need to plug it in the right place. All that you have to do is import the marshaller from your CurrencyJsonProtocol into your Controller like below:

import CurrencyJsonProtocol._

Also make sure you have the below imports as well:

import spray.httpx.SprayJsonSupport._import spray.json.DefaultJsonProtocol._

And spray-json should automatically pick that up.

To understand how it works, you need to understand about implicits in scala. Although it looks like magic when you come from java-world like me, I can assure you it's not.


I´m using Spray support for years. Maybe i should try another one. Anyway, in Spray, a custom formatter for a type is simple. An example of the squants.market.currency https://github.com/typelevel/squants

import squants.market.{ Currency, Money }import squants.market._ trait MoneyJsonProtocol extends DefaultJsonProtocol {  implicit object CurJsonFormat extends JsonFormat[Currency] {    def write(currency: Currency): JsValue = JsString(currency.code)    def read(value: JsValue): Currency = value match {      case JsString(currency) =>        defaultCurrencyMap.get(currency) match {          case Some(c) => c          case None => // throw an exception, for example        }      case _ => // throw another exception, for example    }  }  implicit def toJavaBigDecimal(b: math.BigDecimal): java.math.BigDecimal = b.underlying}


Do you have a JsonFormat[Currency]? If yes, just fix it...

If not, you should follow the doc and create:

  1. as domain model, specific result type to hold the answer e.g. case class CurrencyResult(currency: Currency, code: String)
  2. in trait JsonSupport: a JsonFormat[Currency]
  3. in trait JsonSupport: a JsonFormat[CurrencyResult]

As an alternative to point 1 above, you can probably type your map as: Map[String, JsValue].