Scala foreach member variable

时间:2016-02-03 03:46:13

标签: scala playframework playframework-2.0 case-class

Is there a way to loop for each member variable of a class? It's trivial with Lists and arrays but I have to construct a case class with each json field mapping to a member variable to use the Play framework's Reads/validator API

2 个答案:

答案 0 :(得分:2)

你的意思是这样的:

case class SomeClass(a: Int, b: Int)
SomeClass(1,2).productIterator.foreach{ a => println(a)}

这将为您输出:1 2

或者如果你试图从json构造一个对象。您可以在case类中定义将json反序列化为对象的读取:

override def reads(json: JsValue): JsResult[SomeClass] = JsSuccess(SomeClass(
    (json \ "a").as[Int],
    (json \ "b").as[Int]
  )
  )

然后使用反序列化:

val json = Json.obj() //Your json
json.validate[SomeClass]

json.fold(
  errors => {
    Json.obj("status" -> "Not OK", "message" -> JsError.toJson(errors))
  },
  preset => {
    Json.obj("status" -> "OK")
  }
)

答案 1 :(得分:1)

如果您想比较Json并获得差异,可能更好地使用JsObject方法?

例如fieldSet将所有字​​段作为一组返回。您可以在先前和当前字段集上使用diff来获取更改的字段。这是快速解决方案,没有任何特定的类。