如何检查键是否存在于Json Object中并获取其值 [英] How to check if a key exists in Json Object and get its value
本文介绍了如何检查键是否存在于Json Object中并获取其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说这是我的JSON Object
{
"LabelData": {
"slogan": "AWAKEN YOUR SENSES",
"jobsearch": "JOB SEARCH",
"contact": "CONTACT",
"video": "ENCHANTING BEACHSCAPES",
"createprofile": "CREATE PROFILE"
}
}
我需要知道'video'是否存在于此对象中,如果存在,则需要获取此键的值.我尝试了以下操作,但是我无法获得此钥匙的价值.
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
}
推荐答案
使用以下代码查找键是否在JsonObject
中存在. has("key")
方法用于在JsonObject
中查找键.
Use below code to find key is exist or not in JsonObject
. has("key")
method is used to find keys in JsonObject
.
containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
//get Value of video
String video = containerObject.optString("video");
}
如果使用optString("key")
方法获取String值,则不必担心JsonObject
中是否存在键.
If you are using optString("key")
method to get String value then don't worry about keys are existing or not in the JsonObject
.
这篇关于如何检查键是否存在于Json Object中并获取其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文