Reputation: 91
Currently I have two classes, how to transfer them to Algebraic Data Types? I think I can do something like this case class BlacklistDynamoDBUpdate(ruleName: String, whitelistedAccount, featureName: String)
, but how to use those method in that class?
class DynamoDBUpdateBlacklist {
private var features: Array[BlacklistDynamoDBUpdate] = _
def getFeatures = features
def setFeatures(features: Array[BlacklistDynamoDBUpdate]) = {
this.features = features
}
}
class BlacklistDynamoDBUpdate {
private var ruleName: String = _
private var whitelistedAccount: String = _
private var featureName: String = _
def getFeatureName: String = featureName
def setFeatureName(featureName: String) = {
this.featureName = featureName
}
def getRuleName: String = ruleName
def setRuleName(ruleName: String) = {
this.ruleName = ruleName
}
def getWhitelistedAccounts: String = whitelistedAccount
def setWhitelistedAccounts(whitelistedAccount: String): Unit = {
this.whitelistedAccount = whitelistedAccount
}
}
I transfer a json into scala object, json look like this
"features": [ { "featureName": "***", "ruleName": "***", "whitelistedAccounts": "***" }],
what I want is get those attributes value
Upvotes: 1
Views: 93
Reputation: 1663
If you need to parse json into idiomatic scala code then use simple case classes and library that is design to parse such jsons directly into those case classes (personally I sugest this one https://lihaoyi.com/upickle or this one https://circe.github.io/circe).
here is example code that shows how to use upickle.
import upickle.default.{ReadWriter => RW, macroRW}
final case class DynamoDBUpdateBlacklist(features:Seq[BlacklistDynamoDBUpdate])
final case class BlacklistDynamoDBUpdate(featureName:String, ruleName:String, whitelistedAccounts:String)
object DynamoDBUpdateBlacklist {
implicit val rw: RW[DynamoDBUpdateBlacklist] = macroRW
}
object BlacklistDynamoDBUpdate {
implicit val rw: RW[BlacklistDynamoDBUpdate] = macroRW
}
//use it like that
import upickle.default._
println(
read[DynamoDBUpdateBlacklist]("""
{"features":[{ "featureName": "***", "ruleName": "***", "whitelistedAccounts": "***" }]}
""")
)
//DynamoDBUpdateBlacklist(Vector(BlacklistDynamoDBUpdate(***,***,***)))
https://scalafiddle.io/sf/8eqFEfX/2
Upvotes: 3