1

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 .

JavaGuy
  • 29
  • 6

4 Answers4

0

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

Lokesh
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 27 '21 at 14:08
0

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.

Arutsudar Arut
  • 195
  • 1
  • 13
0

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

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

This will work

Mani
  • 267
  • 2
  • 11
0

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

JSONObject jsonObject = new JSONObject(myJSONString);
String name = jsonObject.optString("name");
Afrifa
  • 31
  • 4