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

Let's say it's mine JSON Object

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

I need to know that either the "video" exists or not in this object, and if it exists, I need to get the value of this key. I tried to follow, but I can not get the value of this key.

 containerObject= new JSONObject(container);
 if(containerObject.hasKey("video")){
  //get Value of video
}
+7
source share
8 answers

Use the code below to find the key exists or does not exist in JsonObject. The method is has("key")used to search for keys in JsonObject.

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

If you use optString("key")String to get the value, don't worry about whether or not keys exist in JsonObject.

+15

:

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

:

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

, .

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();
 }
+2

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) {

    }
+2
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
 }

,

0

Source: https://habr.com/ru/post/1674557/


All Articles