Create rules and validate a JSON Object for org.json library
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONRules {
private static String errorRequired = "{} is required but not found in object.";
private static String errorLength = "The value of {} exceeds the set length in rule.";
private static String errorFormat = "The value of {} does not match with the format set.";
public JSONRules() {
}
public JSONRules(JSONObject customMessages) {
this.errorRequired = hasAttribute(customMessages, "error_required") ? customMessages.getString("error_required") : errorRequired;
this.errorLength = hasAttribute(customMessages, "error_length") ? customMessages.getString("error_length") : errorLength;
this.errorFormat = hasAttribute(customMessages, "error_format") ? customMessages.getString("error_format") : errorFormat;
}
public JSONObject validate(JSONObject obj, JSONArray rule) {
JSONObject response = new JSONObject();
JSONArray errors = new JSONArray();
for (Object o : rule) {
JSONObject r = (JSONObject) o;
if (haveAllRuleAttributes(r)) {
String keyName = r.getString("name");
String format = ".*?";
if (hasAttribute(r, "format")) {
if (!(r.getString("format").length() == 0)) {
format = r.getString("format");
}
}
boolean isRequired = r.getBoolean("required");
if (isRequired && (!hasAttribute(obj, keyName))) {
errors.put(
createError(errorRequired, keyName)
);
} else if (hasAttribute(obj, keyName)) {
if (!String.valueOf(obj.get(keyName)).matches(format)) {
errors.put(
createError(errorFormat, keyName)
);
}
if (hasAttribute(r, "length")) {
int length = r.getInt("length");
if (!(String.valueOf(obj.get(keyName)).length() <= length)) {
errors.put(
createError(errorLength, keyName)
);
}
}
}
} else {
throw new java.lang.Error("All objects in the rule must have the attributes name, format and required.");
}
}
response
.put("errors", errors);
return response;
}
private static JSONObject createError(String message, String keyName) {
JSONObject response = new JSONObject();
response
.put("message", customReplace(message, "{}", keyName));
return response;
}
private static boolean hasAttribute(JSONObject obj, String keyName) {
return obj.has(keyName);
}
private static boolean haveAllRuleAttributes(JSONObject rule) {
return rule.has("name") && rule.has("required");
}
public static String customReplace(String source, String pattern, String replacement) {
if (source == null) {
return "";
}
StringBuffer sb = new StringBuffer();
int idx = -1;
int patIdx = 0;
idx = source.indexOf(pattern, patIdx);
if (idx != -1) {
sb.append(source.substring(patIdx, idx));
sb.append(replacement);
patIdx = idx + pattern.length();
sb.append(source.substring(patIdx));
}
if (sb.length() == 0) {
return source;
} else {
return sb.toString();
}
}
public static void main(String[] args) {
JSONRules jsonRule = new JSONRules(
new JSONObject()
.put("error_required", "{} es requerida pero no se encuentra en el objeto.")
.put("error_length", "El valor de {} excede la longitud establecida.")
.put("error_format", "El valor de {} no coincide con el formato establecido.")
);
JSONObject obj = new JSONObject().put("id", "12312312");
JSONArray rule = new JSONArray()
.put(
new JSONObject()
.put("name", "id")
.put("format", "\\d+")
.put("required", true)
.put("length", 10)
)
.put(
new JSONObject()
.put("name", "sede")
.put("format", "[a-z]")
.put("required", true)
.put("length", 10)
);
System.out.println(jsonRule.validate(obj, rule));
// print {"errors":[{"message":"El valor de codigo excede la longitud establecida."},{"message":"sede es requerida pero no se encuentra en el objeto."}]}
}
}