Last active
April 4, 2019 03:42
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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