Check if key exists in jsonobject before fetching value for that key ?
When you deal with json object you may want to check whether key exists in the jsonobject before fetching value for that key. We can easily check using Google gson JsonObject has() method.
has() method – Class JsonObject
This is the convenience method that can be used to check of a property/member with the specified key is present in the JsonObject or not. This method returns true if the member with specified key exists, otherwise it returns false.
public boolean has(String memberName)
Example
The below example calls method checkIfKeyExists() to check if key exists in jsonobject
package com.sneppets.solution; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class JsonCheckKeyExistsExample { public static void main(String[] args) { JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("name", "john paul"); jsonObj.addProperty("age", "35"); jsonObj.addProperty("city", "Irvine"); System.out.println("Json Object: " + jsonObj); System.out.println("Check if key \"city\" exists : " + checkIfKeyExists(jsonObj.toString(), "city")); System.out.println("Check if key \"state\" exists : " + checkIfKeyExists(jsonObj.toString(), "state")); } private static boolean checkIfKeyExists(String response, String key) { JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject.has(key); } }
Output
Json Object: {"name":"john paul","age":"35","city":"Irvine"} Check if key "city" exists : true Check if key "state" exists : false
GSON – JsonParser
The GSON JsonParser class can parse a JSON string in to tree of JsonElements. Create a JsonParser, then parse JSON string into a tree structure of GSON objects using JsonParser’s parse method.
JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("name", "john paul"); jsonObj.addProperty("age", "35"); jsonObj.addProperty("city", "Irvine"); JsonParser parser = new JsonParser(); JsonElement jsonTree= parser.parse(jsonObj.toString());
Once you parse JSON string in to tree structure then you can extract elements from it using JsonObject instance jsonTree.getAsJsonObject() of the JSON tree structure.
JsonObject jsonObject = jsonTree.getAsJsonObject(); JsonElement city = jsonObject.get("city"); JsonElement state = jsonObject.get("state");
Further Learning
- Pause a job in quartz scheduler ?
- Generate unique Long Id in Java
- Convert List to Map in Java 8 using Streams and Collectors