[java] How to check if a key exists in Json Object and get its value

Let say this is my JSON Object

{
  "LabelData": {
    "slogan": "AWAKEN YOUR SENSES",
    "jobsearch": "JOB SEARCH",
    "contact": "CONTACT",
    "video": "ENCHANTING BEACHSCAPES",
    "createprofile": "CREATE PROFILE"
  }
}

I need to know that either 'video` exists or not in this Object, and if it exists i need to get the value of this key. I have tried following, but i am unable to get value of this key.

 containerObject= new JSONObject(container);
 if(containerObject.hasKey("video")){
  //get Value of video
}

This question is related to java android json performance android-layout

The answer is


Please try this one..

JSONObject jsonObject= null;
try {
     jsonObject = new JSONObject("result........");
     String labelDataString=jsonObject.getString("LabelData");
     JSONObject labelDataJson= null;
     labelDataJson= new JSONObject(labelDataString);
     if(labelDataJson.has("video")&&labelDataJson.getString("video")!=null){
       String video=labelDataJson.getString("video");
     }
    } catch (JSONException e) {
      e.printStackTrace();
 }

JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");

try{
//if key will not be available put it in the try catch block your program 
 will work without error 
String Video=container.getString("video");
}
catch(JsonException e){

 if key will not be there then this block will execute

 } 
 if(video!=null || !video.isEmpty){
  //get Value of video
}else{
  //other vise leave it
 }

i think this might help you


Try

private boolean hasKey(JSONObject jsonObject, String key) {
    return jsonObject != null && jsonObject.has(key);
}

  try {
        JSONObject jsonObject = new JSONObject(yourJson);
        if (hasKey(jsonObject, "labelData")) {
            JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
            if (hasKey(labelDataJson, "video")) {
                String video = labelDataJson.getString("video");
            }
        }
    } catch (JSONException e) {

    }

Use:

if (containerObject.has("video")) {
    //get value of video
}

containerObject = new JSONObject(container);
if (containerObject.has("video")) { 
   //get Value of video
}

From the structure of your source Object, I would try:

containerObject= new JSONObject(container);
 if(containerObject.has("LabelData")){
  JSONObject innerObject = containerObject.getJSONObject("LabelData");
     if(innerObject.has("video")){
        //Do with video
    }
}

JSONObject class has a method named "has". Returns true if this object has a mapping for name. The mapping may be NULL. http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView