如何检查Json对象中是否存在密钥并获取其值

时间:2017-04-11 09:23:01

标签: java android json performance android-layout

说这是我的JSON Object

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

我需要知道此对象中是否存在' video`,如果存在,我需要获取此密钥的值。我试过跟随,但我无法获得这个密钥的价值。

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

8 个答案:

答案 0 :(得分:17)

使用以下代码查找JsonObject中是否存在密钥。 has("key")方法用于查找JsonObject中的密钥。

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

如果您使用optString("key")方法获取字符串值,请不要担心JsonObject中是否存在密钥。

答案 1 :(得分:5)

使用:

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

答案 2 :(得分:4)

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

答案 3 :(得分:3)

从源对象的结构中,我会尝试:

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

答案 4 :(得分:3)

请试试这个......

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

答案 5 :(得分:3)

尝试

SCREEN_WIDTH = container.width();
SCREEN_HEIGHT = SCREEN_WIDTH * aspectRatio;

container.height( SCREEN_HEIGHT );

答案 6 :(得分:3)

JSONObject类有一个名为“has”的方法。 如果此对象具有name的映射,则返回true。映射可以是NULL。 http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

答案 7 :(得分:0)

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
 }

我认为这可能会对你有所帮助

相关问题