我有Json可能有空格,我想修剪。我创建了这个案例类来解析Json.parse(...)。作为[PersonalInfo],但问题是它在第一次失败的读取时失败并且也没有返回JsError。如何定义JsError案例,同时为每个未正确解析的字段保留错误?
case class PersonalInfo(
email: String,
password: String,
firstName: String,
lastName: String
)
object PersonalInfo {
implicit val personalInfoReads = new Reads[PersonalInfo] {
override def reads(json: JsValue): JsResult[PersonalInfo] = {
val email = (json \ "email").as[String].trim
val password = (json \ "password").as[String].trim
val firstName = (json \ "firstName").as[String].trim
val lastName = (json \ "lastName").as[String].trim
JsSuccess(PersonalInfo(email, password, firstName, lastName))
}
}
}
答案 0 :(得分:0)
请参阅我的回答here
用两个词来说:不要在as
中使用reads
。如果解析失败,则抛出异常。使用validate
。您可以通过上面的链接找到示例
<强>更新强>
好吧,如果你想要解决方案..
case class PersonalInfo(email: String,
password: String,
firstName: String,
lastName: String)
object PersonalInfo {
implicit val personalInfoReads = new Reads[PersonalInfo] {
override def reads(json: JsValue): JsResult[PersonalInfo] = {
for {
email <- (json \ "email").validate[String]
password <- (json \ "password").validate[String]
firstName <- (json \ "firstName").validate[String]
lastName <- (json \ "lastName").validate[String]
} yield PersonalInfo(
email.trim(),
password.trim(),
firstName.trim(),
lastName.trim()
)
}
}
}
答案 1 :(得分:0)
我的想法是使用play-json
的标准格式(您也可以使用阅读)然后添加一个函数来修剪它:
case class PersonalInfo(
email: String,
password: String,
firstName: String,
lastName: String
) {
def trimmed() = PersonalInfo(
email.trim,
password.trim,
firstName.trim,
lastName.trim
)
}
object PersonalInfo {
implicit val customWrites: OFormat[PersonalInfo] = Json.format[PersonalInfo]
}
你可以这样使用它:
json.validate[PersonalInfo] match {
case JsSuccess(info: PersonalInfo, _) =>
info.trimmed()
case JsError(errors) =>
error("Other than RunAdapter: " + errors.toString())
}
错误是所有验证错误的列表。