如何检查 JSON 对象中是否存在某个键并获取其值

32

假设这是我的JSON对象

{
  "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
}

你正在使用哪个 JSON 库(名称和版本)? - Sachin Gupta
为什么不使用Gson库将Json解析为Java对象,反之亦然? - Vikas Tiwari
这里的“container”是什么? - rafsanahmad007
容器是简单的JsonObject。我在Android中使用简单的JSONObject。 - dev90
8个回答

60

使用以下代码来查找在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中。

请注意,您只能使用has()检查根键。使用get()获取值。 - Zon
如果你找不到 containerObject.has,可以尝试使用 containerObject.containsKey。我就是这么做的。 - Vijay

11

使用:

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

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

5

从您的源对象结构来看,我会尝试以下操作:

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

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

4

4

尝试

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

    }

这对于JSON中的列表和嵌套列表有效吗? - chocokoala

1
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
 }

我认为这可能对您有所帮助。

如果键不存在,那么你的if条件语句是否会执行? - Chetan Joshi
1
使用异常处理来解决这个问题是非常糟糕的解决方案。 - Selvin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接