JSONObject - How to get a value?

JavaJson

Java Problem Overview


I'm using a java class on http://json.org/javadoc/org/json/JSONObject.html.

The following is my code snippet:

String jsonResult = UtilMethods.getJSON(this.jsonURL, null);
json = new JSONObject(jsonResult);

getJSON returns the following string

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

How do I get the value of 'slogan'?

I tried all the methods listed on the page, but none of them worked.

Java Solutions


Solution 1 - Java

String loudScreaming = json.getJSONObject("LabelData").getString("slogan");

Solution 2 - Java

If it's a deeper key/value you're after and you're not dealing with arrays of keys/values at each level, you could recursively search the tree:

public static String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
    String finalValue = "";
    if (jObj == null) {
        return "";
    }
    
    Iterator<String> keyItr = jObj.keys();
    Map<String, String> map = new HashMap<>();
    
    while(keyItr.hasNext()) {
        String key = keyItr.next();
        map.put(key, jObj.getString(key));
    }
    
    for (Map.Entry<String, String> e : (map).entrySet()) {
        String key = e.getKey();
        if (key.equalsIgnoreCase(findKey)) {
            return jObj.getString(key);
        }
        
        // read value
        Object value = jObj.get(key);
        
        if (value instanceof JSONObject) {
            finalValue = recurseKeys((JSONObject)value, findKey);
        }
    }
    
    // key is not found
    return finalValue;
}

Usage:

JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");

Using Map code from https://stackoverflow.com/a/4149555/2301224

Solution 3 - Java

You can try the below function to get value from JSON string,

public static String GetJSONValue(String JSONString, String Field)
{
       return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");	
}

Solution 4 - Java

This may be helpful while searching keys present in nested objects and nested arrays. And this is a generic solution to all cases.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyClass
{
    public static Object finalresult = null;
    public static void main(String args[]) throws JSONException
    {
        System.out.println(myfunction(myjsonstring,key));
    }

    public static Object myfunction(JSONObject x,String y) throws JSONException
    {
        JSONArray keys =  x.names();
		for(int i=0;i<keys.length();i++)
		{
			if(finalresult!=null)
			{
				return finalresult;                     //To kill the recursion
			}

			String current_key = keys.get(i).toString();

			if(current_key.equals(y))
			{
				finalresult=x.get(current_key);
				return finalresult;
			}
			
			if(x.get(current_key).getClass().getName().equals("org.json.JSONObject"))
			{
				myfunction((JSONObject) x.get(current_key),y);
			}
			else if(x.get(current_key).getClass().getName().equals("org.json.JSONArray"))
			{
				for(int j=0;j<((JSONArray) x.get(current_key)).length();j++)
				{
					if(((JSONArray) x.get(current_key)).get(j).getClass().getName().equals("org.json.JSONObject"))
					{
						myfunction((JSONObject)((JSONArray) x.get(current_key)).get(j),y);
					}
				}
			}
		}
		return null;
	}
}

Possibilities:

  1. "key":"value"
  2. "key":{Object}
  3. "key":[Array]

Logic :

  • I check whether the current key and search key are the same, if so I return the value of that key.
  • If it is an object, I send the value recursively to the same function.
  • If it is an array, I check whether it contains an object, if so I recursively pass the value to the same function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMoonView Question on Stackoverflow
Solution 1 - JavaphihagView Answer on Stackoverflow
Solution 2 - JavaBakerView Answer on Stackoverflow
Solution 3 - Javaravi creedView Answer on Stackoverflow
Solution 4 - JavaNatarajanView Answer on Stackoverflow