在JSON中检查并验证多个密钥

时间:2014-11-20 10:49:28

标签: java json

## json input ##
   像这样:

{ "uuId"        :"val1",
  "logtime"     :"val2",
  "taskid"      :"val3",
  "taskName"    :"val4"
}

##解释##
        我想检查uuId,taskid,taskName这些字段是必填字段。     首先,我想在jsonstring和下一次检查中检查uuId密钥     相应的值是否存在。我如何用java语言检查。     我是用这种方式写的,我不知道这是不是正确的方法。     我想要完善代码。请你提前帮助我。

JSONObject objJsonInput = (JSONObject) JSONSerialize.toJSON(inputJson);
if (!objJsonInput.has("uuId")) {
      System.out.println("Tag is not Found")
    }
/*Again check with another key */
// repeat if process
/*Here check Value is Present or not*/

## Code ##
String uuId=(String)objJsonInput .get("uuId");
if(uuId==""||uuId.equals("")||uuId==null)
{
    System.out.printnln("value not present");
}

检查Json的单个键值。 如果检查继续到我们想要检查的多个字段。

是否可以重写此代码?????你能否提出一些完美的代码片段

1 个答案:

答案 0 :(得分:2)

你可以这样做:

private class FieldsValidation
{
    public boolean allFieldsOk = false;
    public List<String> fieldErrors = new ArrayList<String>();
}

public static final String ERROR_MESSAGE = "The mandatory field %s is not defined !";

public FieldsValidation checkMandatoryFields(JSONObject objJsonInput, String... keys)
{
    FieldsValidation result = new FieldsValidation();
    for (String key : keys)
    {
        if (!objJsonInput.has(key) || objJsonInput.getString(key).isEmpty())
        {
            result.fieldErrors.add(String.format(ERROR_MESSAGE, key));
        }
    }
    result.allFieldsOk = result.fieldErrors.isEmpty();
    return result;
}

然后:

JSONObject objJsonInput = new JSONObject("{\"uuId\" :\"val1\",  \"logtime\"     :\"val2\",  \"taskid\"      :\"val3\",  \"taskName\"    :\"val4\"}");
FieldsValidation validation = checkMandatoryFields(objJsonInput, "uuId", "logtime", "taskid", "taskName");
System.out.println(validation.allFieldsOk);

objJsonInput = new JSONObject("{\"uuId\" :\"val1\",  \"logtime\"     :\"val2\",  \"\"      :\"val3\"}");
validation = checkMandatoryFields(objJsonInput, "uuId", "logtime", "taskid", "taskName");
System.out.println(validation.allFieldsOk);
for (String message : validation.fieldErrors) System.out.println(message); 

打印:

true
false
The mandatory field taskid is not defined !
The mandatory field taskName is not defined !