Example usage for org.json.simple JSONObject get

List of usage examples for org.json.simple JSONObject get

Introduction

In this page you can find the example usage for org.json.simple JSONObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.storageroomapp.client.PageOfEntries.java

/**
 * Unmarshalls an PageOfEntries object from a JSONObject. This method
 * assumes the name-values are immediately attached to the passed object
 * and not nested under a key (e.g. 'array')
 * @param jsonObj the JSONObject/*www .ja v a 2 s. c  o m*/
 * @return an PageOfEntries object, or null if the unpacking failed
 */
static public PageOfEntries parseJSONObject(Collection parent, JSONObject jsonObject) {
    if (jsonObject == null) {
        return null;
    }
    JSONArray jsonArray = (JSONArray) jsonObject.get("resources");
    if (jsonArray == null) {
        return null;
    }

    PageOfEntries el = new PageOfEntries();
    el.currentPage = JsonSimpleUtil.parseJsonIntValue(jsonObject, "@page", 0);
    el.currentPageSize = JsonSimpleUtil.parseJsonIntValue(jsonObject, "@total_resources", 20);
    el.numResultsPages = JsonSimpleUtil.parseJsonIntValue(jsonObject, "@pages", 1);

    el.currentPageEntries = new ArrayList<Entry>();
    @SuppressWarnings("unchecked")
    Iterator<JSONObject> iter = jsonArray.iterator();
    while (iter.hasNext()) {
        JSONObject entryObj = iter.next();
        Entry entry = Entry.parseJSONObject(parent, entryObj);
        if (entry != null) {
            el.currentPageEntries.add(entry);
        }
    }

    return el;
}

From source file:com.storageroomapp.client.util.JsonSimpleUtil.java

/**
 * Convenience method for pulling a Float value off of a JSONObject
 * @param obj the JSONObject received from the server
 * @param key the String key of the value we want
 * @param defaultValue the Float to return if a value is not found (can be null)
 * @return the Float value, or null if not found or not a float
 *//*from ww w.ja v a2s . c o m*/
static public Float parseJsonFloatValue(JSONObject obj, String key, Float defaultValue) {
    if ((obj == null) || (key == null)) {
        return defaultValue;
    }
    Float value = defaultValue;
    Object valueObj = obj.get(key);
    if (valueObj != null) {
        String valueStr = valueObj.toString();
        try {
            value = Float.parseFloat(valueStr);
        } catch (NumberFormatException nfe) {
            // TODO log
            value = defaultValue;
        }
    }
    return value;

}

From source file:mml.handler.json.Dialect.java

private static boolean compareObjects(JSONObject o1, JSONObject o2) {
    boolean res = true;
    Set<String> keys = o1.keySet();
    Iterator<String> iter = keys.iterator();
    while (iter.hasNext() && res) {
        String key = iter.next();
        Object obj1 = o1.get(key);
        Object obj2 = o2.get(key);
        if (obj1 != null && obj2 != null && obj1.getClass().equals(obj2.getClass())) {
            if (obj1 instanceof String)
                res = obj1.equals(obj2);
            else if (obj1 instanceof Number)
                return obj1.equals(obj2);
            else if (obj1 instanceof JSONArray)
                res = compareArrays((JSONArray) obj1, (JSONArray) obj2);
            else if (obj1 instanceof JSONObject)
                res = compareObjects((JSONObject) obj1, (JSONObject) obj2);
            else if (obj1 instanceof Boolean)
                res = obj1.equals(obj2);
            else// w  ww .j  a v a 2  s  . c  o m
                res = false;
        } else
            res = false;
    }
    return res;
}

From source file:com.domsplace.DomsCommands.Objects.Chat.DomsChatObject.java

public static DomsChatObject createFromString(String msg) {
    try {/*  w  w  w  .  j  a v a 2s. co  m*/
        JSONParser parser = new JSONParser();
        JSONObject object = (JSONObject) parser.parse(msg);

        DomsChatObject obj = new DomsChatObject();

        for (Object item : object.keySet()) {
            Object value = object.get(item);
            String key = item.toString();
        }

        return obj;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.storageroomapp.client.util.JsonSimpleUtil.java

/**
 * Convenience method for pulling a Integer value off of a JSONObject
 * @param obj the JSONObject received from the server
 * @param key the String key of the value we want
 * @param defaultValue the Integer to return if a value is not found (can be null)
 * @return the Integer value, or null if not found or not an int
 *//*from  w w  w  .  j  a v a 2s  . c o  m*/
static public Integer parseJsonIntValue(JSONObject obj, String key, Integer defaultValue) {
    if ((obj == null) || (key == null)) {
        return defaultValue;
    }
    Integer value = defaultValue;
    Object valueObj = obj.get(key);
    if (valueObj != null) {
        String valueStr = valueObj.toString();
        try {
            value = Integer.parseInt(valueStr);
        } catch (NumberFormatException nfe) {
            // TODO log
            value = defaultValue;
        }
    }
    return value;
}

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * /*from ww  w .j ava 2 s .co  m*/
 * @param latitude
 * @param longitude
 * @return 
 */
public static HashMap reverse(double latitude, double longitude) {
    HashMap a = new HashMap();
    try {
        //URL url=new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude));            
        URL url = new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng="
                + String.valueOf(latitude) + "," + String.valueOf(longitude));
        URL file_url = new URL(
                url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery()));
        //BufferedReader lector=new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedReader lector = new BufferedReader(new InputStreamReader(file_url.openStream()));
        String textJson = "", tempJs;
        while ((tempJs = lector.readLine()) != null)
            textJson += tempJs;
        if (textJson == null)
            throw new Exception("Don't found item");
        JSONObject google = ((JSONObject) JSONValue.parse(textJson));
        a.put("status", google.get("status").toString());
        if (a.get("status").toString().equals("OK")) {
            JSONArray results = (JSONArray) google.get("results");
            JSONArray address_components = (JSONArray) ((JSONObject) results.get(2)).get("address_components");
            for (int i = 0; i < address_components.size(); i++) {
                JSONObject items = (JSONObject) address_components.get(i);
                //if(((JSONObject)types.get(0)).get("").toString().equals("country"))
                if (items.get("types").toString().contains("country")) {
                    a.put("country", items.get("long_name").toString());
                    a.put("iso", items.get("short_name").toString());
                    break;
                }
            }
        }
    } catch (Exception ex) {
        a = null;
        System.out.println("Error Google Geocoding: " + ex);
    }
    return a;
}

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Gets the recent challenges and splits them to active and past challenges
 * Maximum 3 past challenges and all active challenges will be returned
 * @param sessionId//from ww w  . jav a  2s.  c om
 * @param username
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static JSONObject getProcessedChallengesM2(String sessionId, String username)
        throws MalformedURLException, IOException {
    JSONArray recentChallenges = getRecentParticipantChallengesByUsername(sessionId, username);
    JSONArray activeChallenges = new JSONArray();
    JSONArray pastChallenges = new JSONArray();

    Iterator<JSONObject> iterator = recentChallenges.iterator();
    while (iterator.hasNext()) {
        JSONObject participantChallenge = iterator.next();
        JSONObject challenge = (JSONObject) participantChallenge.get("Challenge__r");
        if (challenge.get("Status__c").equals(PSContants.STATUS_CREATED)) { //active challenge
            activeChallenges.add(participantChallenge);
            JSONArray categories = getCategoriesByChallenge(sessionId,
                    (String) participantChallenge.get("Challenge__c"));
            participantChallenge.put("categories", categories);
        } else { //past challenges
            if (pastChallenges.size() < 3) {
                pastChallenges.add(participantChallenge);
                JSONArray categories = getCategoriesByChallenge(sessionId,
                        (String) participantChallenge.get("Challenge__c"));
                participantChallenge.put("categories", categories);
            }
        }
    }
    JSONObject challenges = new JSONObject();
    challenges.put("activeChallenges", activeChallenges);
    challenges.put("pastChallenges", pastChallenges);
    challenges.put("totalChallenges", getChallengeCountByUser(sessionId, username));
    return challenges;
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsLocalSchemaExtractor.java

/****
 * This function counts the total occurrences of keys, in the json records files
 *  /*from  ww  w .  j  ava  2 s.c  o  m*/
 * @param input_filename path to a json file
 * @return a HashMap with the keys / total counts pairs
 */
private static KeyValueCounter countKeysInJsonRecordsFile(String input_filename) {
    InputStream fis;
    BufferedReader bufferedReader;
    String line;
    JSONParser jsonParser = new JSONParser();
    KeyValueCounter keyValueCounter = new KeyValueCounter();
    String jsonValue = "";
    try {
        fis = new FileInputStream(input_filename);
        bufferedReader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
        while ((line = bufferedReader.readLine()) != null) {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
            Set<String> keyset = jsonObject.keySet();
            for (String jsonkey : keyset) {
                if (jsonObject.get(jsonkey) != null) {
                    jsonValue = (String) jsonObject.get(jsonkey).toString();
                    if (jsonValue == null || jsonValue == "") {
                        jsonValue = "";
                    }
                    int lenValue = jsonValue.length();
                    keyValueCounter.incrementKeyCounter(jsonkey);
                    keyValueCounter.putValueLength(jsonkey, lenValue);
                } else {
                    if (jsonkey.compareTo("user_agent") != 0) {
                        logger.error("Errot typing to get jsonkey " + jsonkey);
                    }

                }
            }
        }
        bufferedReader.close();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //System.out.println(keyCounter.toString());
    //System.out.println(sortHashByKey(keyCounter));      
    return keyValueCounter;
}

From source file:com.lifetime.util.TimeOffUtil.java

protected static List<RepliconTimeOff> createTimeOffList(String response) throws ParseException {

    JSONParser parser = new JSONParser();

    JSONObject jsonObject = (JSONObject) parser.parse(response);

    JSONObject d = (JSONObject) jsonObject.get("d");

    JSONArray rows = (JSONArray) d.get("rows");

    List<RepliconTimeOff> list = new ArrayList<RepliconTimeOff>();

    for (Object row : rows) {
        JSONArray cells = (JSONArray) ((JSONObject) row).get("cells");

        JSONObject owner = (JSONObject) cells.get(0);
        String employeeName = (String) owner.get("textValue");

        JSONObject department = (JSONObject) cells.get(1);
        String departmentName = (String) department.get("textValue");

        JSONObject ptoType = (JSONObject) cells.get(2);
        String ptoTypeName = (String) ptoType.get("textValue");

        SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy");

        JSONObject startDateJson = (JSONObject) cells.get(3);
        String startDateString = (String) startDateJson.get("textValue");

        Date startDate = null;/*from   w w  w  .ja  v  a2 s. c o m*/

        try {
            startDate = dateFormat.parse(startDateString);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }

        JSONObject endDateJson = (JSONObject) cells.get(3);
        String endDateString = (String) endDateJson.get("textValue");

        Date endDate = null;

        try {
            endDate = dateFormat.parse(endDateString);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }

        JSONObject approvedJson = (JSONObject) cells.get(5);
        String approvedString = (String) approvedJson.get("textValue");

        boolean approved = approvedString.equals("Approved") ? true : false;

        RepliconTimeOff repliconTimeOff = new RepliconTimeOffImpl(employeeName, departmentName, startDate,
                endDate, ptoTypeName, approved);

        list.add(repliconTimeOff);
    }

    return list;
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static String getToken(String host, String tenant, String username, String password) throws IOException {

    String url = String.format("http://%s:5000/v2.0/tokens", host);
    String body = String.format(
            "{\"auth\": {\"tenantName\": \"%s\", \"passwordCredentials\": {\"username\": \"%s\", \"password\": \"%s\"}}}",
            tenant, username, password);

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String responseStr = sendPOST(obj, con, body);
    JSONObject responseJSON = (JSONObject) JSONValue.parse(responseStr);
    String tokenId = (String) ((JSONObject) ((JSONObject) responseJSON.get("access")).get("token")).get("id");

    return tokenId;
}