Home > Mobile >  How to handle the case when field is not present in Object Java?
How to handle the case when field is not present in Object Java?

Time:10-28

I have an object something like this in my database and now my requirement is to find the value of particular field such as name and if present return true,

{
    "_id" : "123",
    "name" : "Team"
}

but in some case the field name itself doesn't exist. Sample can be something like this:

{
    "id":1234
}

In this case I need to return false.

How can I validate if name field exist in particular object?

I was trying to use StringUtils method something like this StringUtils.isBlank(obj.getName);
But its throwing It is throwing java.lang.NullPointerException .

CodePudding user response:

You can use Json schema validator. If your json will be in specific format. Please have a look at Jackson library.

CodePudding user response:

JSONObject class has a method named "has". try this way,

if (json.has("name")) {
   String status = json.getString("name"));
}

This will work

CodePudding user response:

You can use Gson Java library to serialize and deserialize Java objects to JSON (as given below).

Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(object, JsonObject.class);

Then, you can use the has method in JsonObject, to check if the key exists in it.

jsonObject.has(key)

Example:

Below is a method to check if given key exists in given json string, and get it's value.

(Instead of String, you can use your object as well. Here, I am considering the jsonStr as a String object, for better understanding.)

private String getValueFromJsonForGivenKey(String key, String jsonStr) {
    Gson gson = new Gson();
    JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class);
    if (jsonObject.has(key)) {
        // The given JSON string has the given key
        String value = jsonObject.get(key).getAsString();
        return value;
    }
    return null;
}

For key id and for jsonStr { "id": "1234" }, we get 1234.

For key name and for jsonStr { "id": "1234" }, we get null.

CodePudding user response:

What you can do is to use JSONObject's opt method eg.

JSONObject jsonObject = new JSONObject(myJSONString);
String name = jsonObject.optString("name");
  • Related