karthik.A.M
karthik.A.M

Reputation: 135

Check and Validate Multiple keys Exists in JSON i

## json input ##
Like this :

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

## Explanation##
i want to check uuId,taskid,taskName these fields are mandatory fields. First i want check uuId key is present in jsonstring and next check corresponding value is present or not. How i am checkwith in java language. i am wrote in this way i don't know this is correct way or not. I want to perfect code.Could you help me thanks in advance.

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");
}

Checking indiviual key values of Json. if check continues upto howmany fields we want to check.

Is it possible to rewrite this code?????could you suggest some perfect snippet code

Upvotes: 0

Views: 2389

Answers (1)

ToYonos
ToYonos

Reputation: 16833

You can do something like that :

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;
}

And then :

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); 

It prints :

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

Upvotes: 2

Related Questions