Skip to content

Instantly share code, notes, and snippets.

@odenzo
Last active April 4, 2019 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odenzo/e47730b01ee0aabec565b9da5b04ed03 to your computer and use it in GitHub Desktop.
Save odenzo/e47730b01ee0aabec565b9da5b04ed03 to your computer and use it in GitHub Desktop.
Simple example of using Circe Decoder with prepare to preprocesses Json (JSonObjects in this case)
import io.circe._
// Generalized in real-life
def fieldNameChangeEx(in: JsonObject): JsonObject = {
val fieldName = "type"
val newName = "tipe"
// Not sure what happens on missing fieldName or fieldName = null
val updated: Option[JsonObject] = in(fieldName)
.map(oldVal ⇒ in.add(newName, oldVal))
.map(jo ⇒ jo.remove(fieldName))
updated.getOrElse(in)
}
def prepareByMungingJsonObject(fn: JsonObject => JsonObject)(in: ACursor): ACursor = {
in.withFocus(json ⇒ json.mapObject(jobj ⇒ fn(jobj)))
}
val myFunc : JsonObject ⇒ JsonObject = fieldNameChangeEx
val myPrepareStyle1: ACursor ⇒ ACursor = prepareByMungingJsonObject(myFunc)
val myPrepareStyle2: ACursor ⇒ ACursor = prepareByMungingJsonObject(fieldNameChangeEx)
val decoder: Decoder[FieldType] = deriveDecoder[FieldType].prepare(myPrepareStyle1)
implicit val decodeFieldType: Decoder[FieldType] =
Decoder.forProduct5("nth", "isVLEncoded", "isSerialized", "isSigningField", "type")(FieldType.apply)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment