scalapb-json / scalapb-circe

Json/Protobuf convertors for ScalaPB use circe
MIT License
43 stars 11 forks source link

Allow for supplying custom encoders to ScalaPB ones #15

Open s5bug opened 5 years ago

s5bug commented 5 years ago

For example, the API I'm using requires me to send Map[String, A] as {"key": $string, "value": $a} and not {$string: $a}. I've created a custom Map[String, A: Encoder] to do this but it isn't picked up by scalapb-circe.

s5bug commented 5 years ago

Minimal case:

case class KeyValuePair[T: Encoder](key: String, value: T)

implicit def encodeKVPair[T: Encoder]: Encoder[KeyValuePair[T]] = (a: KeyValuePair[T]) => JsonObject("key" -> a.key.asJson, "value" -> a.value.asJson).asJson

implicit def customMapEncoder[T: Encoder]: Encoder[Map[String, T]] = (a: Map[String, T]) => {
  a.toList.map { case (k, v) => KeyValuePair(k, v) }.asJson
}

def pack[I <: GeneratedMessage with Message[I]](i: I): MessageData = JsonFormat.toJson(i)

Call pack with some sort of pb message that has a Map value.