如何实现条件JSON验证器

如何实现条件JSON验证器

本文介绍了播放:如何实现条件JSON验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Play应用程序具有这样的JSON验证器:

My Play application has a JSON validator like this:

val validateAccount = (
  ((__ \ 'id).json.pickBranch) ~
  ((__ \ 'name).json.pickBranch) ~ // mandatory
  ((__ \ 'mobile).json.pickBranch or emptyObj) ~ // optional
  ...
).reduce

上面的验证器接受JSON,该JSON至少包含一个id和一个名称(可选).是否可以根据条件将字段设为必填项?例如,当条件为true时如何使name为强制性,而当条件为false时如何使其为可选?

The validator above accepts JSON that contains at least an id and optionally a name. Is it possible to make a field mandatory depending on a condition? For instance, how do I make name mandatory when a condition is true and keep it optional when that condition is false?

def validateAccount(condition: Boolean) = (
  ((__ \ 'id).json.pickBranch) ~
  ((__ \ 'name).json.pickBranch if (condition) or emptyObj else ???) ~
  ((__ \ 'mobile).json.pickBranch or emptyObj) ~
  ...
).reduce

我希望emptyObj当且仅当coditiontrue时– emptyObj仅代表一个空节点:

I want emptyObj if and only if codition is trueemptyObj just represents an empty node:

val emptyObj = __.json.put(Json.obj())

[不良]解决方案可能是这样的:

A [bad] solution could be something like this:

def validateAccount(condition: Boolean) = {
  (if (condition) {
    ((__ \ 'id).json.pickBranch) ~
    ((__ \ 'name).json.pickBranch) ~ // mandatory
    ((__ \ 'mobile).json.pickBranch or emptyObj) ~ // optional
    ...
  } else {
    ((__ \ 'id).json.pickBranch) ~
    ((__ \ 'name).json.pickBranch or emptyObj) ~ // now this is optional
    ((__ \ 'mobile).json.pickBranch or emptyObj) ~ // optional
    ...
  }).reduce
}

我需要条件JSON验证的原因是,当我的REST api获得插入请求时,JSON必须完整,而当其获得更新请求时,仅应提供要更新的字段.

The reason I need conditional JSON validation is that when my REST api gets an insert request, the JSON has to be complete, while when it gets an update request, only the field to be updated should be provided.

推荐答案

好的...这是解决方案:

OK... here is the solution:

package object typeExtensions {

  import play.api.libs.json._
  import play.api.libs.functional.syntax._

  implicit class ReadsExtensions(reads: Reads[JsObject]) extends AnyVal {

    def orEmpty = reads | __.put(Json.obj())
    def orEmptyIf(b: Boolean) = if (b) orEmpty else reads
  }
}

object MyObject {

  def validateAccount(update: Boolean) = (
    ((__ \ 'id).json.pickBranch orEmptyIf update) ~ // can be empty only if update is true
    ((__ \ 'name).json.pickBranch orEmtpy) ~        // can be always empty
    ((__ \ 'mobile).json.pickBranch orEmpty) ~      // can be always empty
    ...
  ).reduce

  ...
}

我希望对您有所帮助;-)

I hope that helps ;-)

这篇关于播放:如何实现条件JSON验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:12