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

dev*_*v90 14 java performance android json android-layout

让我说这是我的 JSON Object

{
  "LabelData": {
    "slogan": "AWAKEN YOUR SENSES",
    "jobsearch": "JOB SEARCH",
    "contact": "CONTACT",
    "video": "ENCHANTING BEACHSCAPES",
    "createprofile": "CREATE PROFILE"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

 containerObject= new JSONObject(container);
 if(containerObject.hasKey("video")){
  //get Value of video
}
Run Code Online (Sandbox Code Playgroud)

Che*_*shi 27

使用下面的代码来查找密钥是否存在JsonObject.has("key")方法用于查找键JsonObject.

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

如果您使用optString("key")方法获取String值,则不必担心密钥是否存在JsonObject.


Tys*_*bba 7

使用:

if (containerObject.has("video")) {
    //get value of video
}
Run Code Online (Sandbox Code Playgroud)


Muk*_*r S 5

containerObject = new JSONObject(container);
if (containerObject.has("video")) { 
   //get Value of video
}
Run Code Online (Sandbox Code Playgroud)


Tar*_*riq 5

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

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


Che*_*pad 5

请试试这个..

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();
 }
Run Code Online (Sandbox Code Playgroud)


Fat*_* km 5

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