Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let say this is my JSON Object

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

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 } 
like image 670
dev90 Avatar asked Apr 11 '17 09:04

dev90


People also ask

How do you check if a key exists in JSON object and get its value?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in 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 . Note that you can check only root keys with has(). Get values with get().

Does JSON object allow duplicate keys?

We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.


2 Answers

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

If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject.

like image 108
Chetan Joshi Avatar answered Sep 19 '22 12:09

Chetan Joshi


Use:

if (containerObject.has("video")) {     //get value of video } 
like image 25
TysonSubba Avatar answered Sep 20 '22 12:09

TysonSubba