How to check if a JSON key exists?
So, I get some JSON values from the server but I don’t know if there will be a particular field or not. So like:
13 Answers 13
JSONObject class has a method named «has»:
Returns true if this object has a mapping for name. The mapping may be NULL.
@Eido95 having an Integer as a key sounds like bad practice. JSON should be with a String key and a value of whatever you need.
@Eido95, I believe for an integer there is always a value, every time you declare an integer, you have to initialize it with a value.
You can check this way where ‘HAS’ — Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) < String status = json.getString("status")); >if (json.has("club"))
You can also check using ‘isNull’ — Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club")) String club = json.getString("club"));
you could JSONObject#has , providing the key as input and check if the method returns true or false . You could also
use optString instead of getString :
Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists
Although this method of may be of use for others, this does not return if the value exists. If getString would have returned an empty string, optString would also return an empty string. Assumption would then have you believe that the property isn’t available in OP’s situation.
just before read key check it like before read
JSONObject json_obj=new JSONObject(yourjsonstr); if(!json_obj.isNull("club")) < //it's contain value to be read operation >else < //it's not contain key club or isnull so do this operation here >
isNull function definition
Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
official documentation below link for isNull function
public boolean has(String key)
Determine if the JSONObject contains a specific key.
JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs if (JsonObj.has("address")) < //Checking address Key Present or not String get_address = JsonObj .getString("address"); // Present Key >else < //Do Your Staff >
A better way, instead of using a conditional like:
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString(«key») method will return an empty String if the key does not exist and won’t, therefore, throw you an exception.
let json=yourJson if(json.hasOwnProperty(yourKey))
Json has a method called containsKey() .
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json"); InputStream is = new FileInputStream(jsonInputFile); JsonReader reader = Json.createReader(is); JsonObject frameObj = reader.readObject(); reader.close(); if frameObj.containsKey("person") < //Do stuff >
I used hasOwnProperty('club') var myobj = < "regatta_name":"ProbaRegatta", "country":"Congo", "status":"invited" >; if ( myobj.hasOwnProperty("club")) // do something with club (will be false with above data) var data = myobj.club; if ( myobj.hasOwnProperty("status")) // do something with the status field. (will be true with above ..) var data = myobj.status;
works in all current browsers.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile); if (object.containskey("key")) < object.get("key"); //etc. etc. >
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces <> and using has(String key) doesn’t make any sense.
So you can directly write if (jsonObject.length() > 0) and do your things.
Search JSON elements with in a JSONArray
I want to implement a function in Java which can take the JSON array, value and return a JSON String with all elements with passed value, Example:
public String returnSearch(JSONArray array, String searchValue) < // let us say if the searchValue equals John, this method // has to return a JSON String containing all objects with // the name John >
iterate through elements of your JSONArray, check their name key, and if it matches — add them to another JSONArray
3 Answers 3
public String returnSearch(JSONArray array, String searchValue) < JSONArray filtedArray = new JSONArray(); for (int i = 0; i < array.length(); i++) < JSONObject obj= null; try < obj = array.getJSONObject(i); if(obj.getString("name").equals(searchValue)) < filtedArray.put(obj); >> catch (JSONException e) < e.printStackTrace(); >> String result = filtedArray.toString(); return result; >
Codes are self explanatory, so comments are omitted, hope it helpful.
You can create ArraList of HashMap to store you complete JSON data.
Here is example code.
public String MethodName(String json, String search) < try < JSONArray array = new JSONArray(); JSONObject object = new JSONObject(); JSONArray jsonArray = new JSONArray(json); ArrayList> data = new ArrayList<>(); for (int i = 0 ; i < jsonArray.length(); i++) < JSONObject jsonObject = jsonArray.getJSONObject(i); if (search.equalsIgnoreCase(jsonObject.getString("name"))) < array.put(jsonObject); >> return array.toString(); > catch (Exception e) < e.printStackTrace(); >return null; >
Create a pojo class i.e User
class User < String name; String city; String age; // constructor with empty body public User()<>public User(String name,String city,String age) < this.name = name; this.city = city; this.age = age; >// create getter and setter here public String getName() < return this.name; >public String getCity() < return this.city; >public String getAge() < return this.age; >>
Now create your desired method with return type User Class
public User getUserInfo(String json, String search) < User user; try < JSONArray jsonArray = new JSONArray(json); for (int i = 0 ; i < jsonArray.length(); i++) < JSONObject jsonObject = jsonArray.getJSONObject(i); if (search.equalsIgnoreCase(jsonObject.getString("name"))) < String name = jsonObject.getString("name"); String city = jsonObject.getString("city"); String city = jsonObject.getString("age"); user = new User(name, city, age); >> return user; > catch (Exception e)
Now call method and get data from User class object
User user = obj.getUserInfo(json, search); String name = user.getName(); String city = user.getCity(); String age = user.getAge();
Google Gson JsonArray contains(JsonElement element)
Google Gson JsonArray contains(JsonElement element) Returns true if this array contains the specified element.
Introduction
Syntax
The method contains() from JsonArray is declared as:
public boolean contains(JsonElement element)
The method contains() has the following parameter:
The method contains() returns true if this array contains the specified element.
Example
The following code shows how to use JsonArray from com.google.gson.
Specifically, the code shows you how to use Google Gson JsonArray contains(JsonElement element)
// Filters out all businesses that aren't restaurants import com.google.gson.*; import java.util.*; import java.io.*; public class CreateRestaurantFile < public static void main(String[] args) throws IOException < Scanner sc = new Scanner(new File("yelp_academic_dataset_business.json")); FileWriter out = new FileWriter(new File("yelp_academic_dataset_business_restaurants.json")); JsonParser parser = new JsonParser(); int counter = 0; while (sc.hasNextLine()) < if (counter % 1000 == 0) System.out.println(counter); String line = sc.nextLine(); JsonElement element = parser.parse(line); JsonArray cats = element.getAsJsonObject().getAsJsonArray("categories"); JsonPrimitive r = new JsonPrimitive("Restaurants"); if (cats.contains(r)) out.write(line + "\n"); >/*w w w . d e m o 2 s . c o m */ counter++; > sc.close(); out.close(); > >
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; public class JsonArrayExample < public static void main(String[] args) < JsonArray array = new JsonArray(); array.add(new JsonPrimitive("StringA")); JsonObject a = new JsonObject(); a.add("key1", new JsonPrimitive("value1")); JsonObject b = new JsonObject(); b.add("key2", new JsonPrimitive("value2")); array.add(a);// w w w . d e m o2 s . c o m System.out.println(array.toString()); // prints ["StringA",] // the new methods now System.out.println(array.contains(a));// prints true System.out.println(array.contains(b));// prints false array.set(1, b); System.out.println(array.toString()); // prints ["StringA",]. the value at index 1 is // overwritten System.out.println(array.remove(a)); // prints false since a is not // present in the array System.out.println(array.remove(1)); // prints , the element that is removed System.out.println(array.toString()); //prints ["StringA"] > >
// Uses JavaScript engine that ships with jdk e.g., // http://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/ import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /* Nashorn Javascript Libraries */ import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class RunJavascript < // Small load-file method private static String readFile(String fileName) throws IOException < return new String(Files.readAllBytes(Paths.get(fileName))); >/*w w w . d e m o 2 s . c o m */ // Usage private static void usage() < System.err.println( "Q*cert Javascript Runner expects two options:\n [-runtime filename] for the Q*cert Javscript runtime\n [-input filename] for the input data\nAnd the Javascript file\n"); > // Main public static void main(String[] args) throws Exception < if (args.length != 5) < usage(); >ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); String inputFile = null; String runtimeFile = null; for (int i = 0; i < args.length; i++) < String arg = args[i]; // Must have a -input option for the input JSON if ("-input".equals(arg)) < inputFile = args[i + 1]; i++; >// Must have a -runtime option for the Q*cert Javascript runtime else if ("-runtime".equals(arg)) < runtimeFile = args[i + 1]; i++; >else < // Load input JSON, which may include schema (inheritance) and output JsonArray output; if (inputFile != null) < JsonArray[] outputHolder = new JsonArray[1]; String funCall = loadIO(inputFile, outputHolder); engine.eval(funCall); output = outputHolder[0]; > else < throw new IllegalArgumentException("Input Data File Missing"); > // Load Q*cert Javascript runtime if (runtimeFile != null) < engine.eval(readFile(runtimeFile)); >else < throw new IllegalArgumentException("Runtime File Missing"); > engine.eval(new java.io.FileReader(arg)); // Evaluate the compiler query + stringify the result engine.eval("var result = JSON.stringify(query(world));"); // Get the result String result = (String) engine.get("result"); // Print the result System.out.println(result); // Validate the result if (output != null) < if (validate(result, output)) System.out.println("As expected."); else System.out.println("Result was not as expected. Expected result: " + output); > > > > // Validate a result when output has been provided as a JsonArray (optional) private static boolean validate(String result, JsonArray expected) < JsonArray actual = new JsonParser().parse(result).getAsJsonArray().get(0).getAsJsonArray(); if (actual.size() != expected.size()) return false; for (JsonElement e : actual) if (!expected.contains(e)) return false; for (JsonElement e : expected) if (!actual.contains(e)) return false; return true; > // Load input, which may optionally also include inheritance and output if actually an "I/O" file. private static String loadIO(String inputFile, JsonArray[] output) throws IOException < JsonElement rawInput = new JsonParser().parse(new FileReader(inputFile)); if (rawInput.isJsonObject()) < // All acceptable input formats are JSON objects JsonObject input = rawInput.getAsJsonObject(); // Attempt to obtain inheritance (else use empty array) JsonArray inheritance = null; if (input.has("schema")) < JsonObject schema = input.get("schema").getAsJsonObject(); if (schema.has("hierarchy")) inheritance = schema.get("hierarchy").getAsJsonArray(); else if (schema.has("inheritance")) inheritance = schema.get("inheritance").getAsJsonArray(); > if (inheritance == null) inheritance = new JsonArray(); // Attempt to obtain output (else leave output argument as is) if (input.has("output")) output[0] = input.get("output").getAsJsonArray(); // Let input contain just the input object if (input.has("input")) input = input.get("input").getAsJsonObject(); // Assemble result return String.format("var world = %s;%nvar inheritance = %s;", input, inheritance); > throw new IllegalArgumentException("Input file does not have a recognized format"); > >
Related
- Google Gson JsonArray toString()
- Google Gson JsonArray addAll(JsonArray array)
- Google Gson JsonArray set(int index, JsonElement element)
- Google Gson JsonArray contains(JsonElement element)
- Google Gson JsonArray getAsJsonArray()
- Google Gson JsonArray getAsString()
- Google Gson JsonArray remove(JsonElement element)
demo2s.com | Email: | Demo Source and Support. All rights reserved.
JSON — Check if an array exists
I have a JSON file filled with some arrays. I was wondering if anyone knows how i can check if a specifik array exists in the file. EDIT: This is how my file is organized.
I want to search through the arrays and check if a specifik array exists or not. If it doese then I will serialize it. > Thanks in advance for all help
Are there any special performance concerns? Is it reasonable to just deserialize the entire JSON contents, and then determine whether the array exists? Or for a legitimate performance concern, are you trying to just deserialize the small part of the JSON contents that has the target array?
3 Answers 3
Following is an example of an approach you could take using Jackson. It uses the same JSON structure presented in the latest question updates, along with a matching Java data structure. This allows for very easy deserialization, with just one line of code.
I chose to just deserialize the JSON array to a Java List. It’s very easy to change this to use a Java array instead.
(Note that there are issues with this JSON structure that I suggest changing, if it’s in your control to change it.)
import java.io.File; import java.util.List; import java.util.Map; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.map.ObjectMapper; public class Foo < public static void main(String[] args) throws Exception < ObjectMapper mapper = new ObjectMapper(); // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY)); // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class); // look for the target named array2 if (thing.objects.containsKey("array2")) < // an element with the target name is present, make sure it's a list/array if (thing.objects.get("array2") instanceof List) < // found it Listtarget = thing.objects.get("array2"); OtherThing otherThing = target.get(0); System.out.println(otherThing.element1); // value1 System.out.println(otherThing.element2); // value2 System.out.println(otherThing.element3); // value3 > // else do something > // else do something > > class Thing < Mapobjects; > class OtherThing