Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:org.owasp.goatdroid.fourgoats.rest.searchforfriends.SearchForFriendsResponse.java

static public ArrayList<HashMap<String, String>> parseSearchForFriendsResponse(String response) {

    JSONObject json;
    ArrayList<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
    String errors = "";

    try {/*w  w  w. ja  v  a  2s  . c o  m*/
        json = new JSONObject(response);
        if (json.getString("success").equals("true")) {
            JSONArray friendArray = json.getJSONArray("users");
            for (int count = 0; count < friendArray.length(); count++) {
                HashMap<String, String> resultsMap = new HashMap<String, String>();
                resultsMap.put("success", "true");
                HashMap<String, String> friend = new HashMap<String, String>();

                if (friendArray.getJSONObject(count).has("userID"))
                    friend.put("userID", (String) friendArray.getJSONObject(count).get("userID"));
                if (friendArray.getJSONObject(count).has("userName"))
                    friend.put("userName", (String) friendArray.getJSONObject(count).get("userName"));
                if (friendArray.getJSONObject(count).has("firstName"))
                    friend.put("firstName", (String) friendArray.getJSONObject(count).get("firstName"));
                if (friendArray.getJSONObject(count).has("lastName"))
                    friend.put("lastName", (String) friendArray.getJSONObject(count).get("lastName"));
                results.add(resultsMap);
                if (friend.size() > 0)
                    results.add(friend);
            }
        } else {
            HashMap<String, String> resultsMap = new HashMap<String, String>();
            resultsMap.put("success", "false");
            try {
                JSONArray errorArray = json.getJSONArray("errors");

                for (int count = 0; count < errorArray.length(); count++)
                    errors += errorArray.getString(count).toString() + "\n\n";

            } catch (JSONException e) {
                errors += json.getString("errors");
            }
            resultsMap.put("errors", errors);
            results.add(resultsMap);
        }
    } catch (JSONException e) {
        try {
            json = new JSONObject(response);
            HashMap<String, String> resultsMap = new HashMap<String, String>();
            resultsMap.put("success", "true");
            results.add(resultsMap);
            HashMap<String, String> friend = new HashMap<String, String>();
            if (json.getJSONObject("users").has("userID"))
                friend.put("userID", (String) json.getJSONObject("users").get("userID"));
            if (json.getJSONObject("users").has("userName"))
                friend.put("userName", (String) json.getJSONObject("users").get("userName"));
            if (json.getJSONObject("users").has("firstName"))
                friend.put("firstName", (String) json.getJSONObject("users").get("firstName"));
            if (json.getJSONObject("users").has("lastName"))
                friend.put("lastName", (String) json.getJSONObject("users").get("lastName"));
            if (friend.size() > 0)
                results.add(friend);

        } catch (JSONException e1) {
            /*
             * We don't care if it falls through here.
             */
            e1.getMessage();
        }
    }
    return results;
}

From source file:com.rapid.actions.Navigate.java

public Navigate(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call super constructor to set xml version
    super();/*from  w  w w.ja v a 2  s .  c  o  m*/
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties (except for sessionVariables)
        if (!"sessionVariables".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }
    // get the inputs collections
    JSONArray jsonInputs = jsonAction.optJSONArray("sessionVariables");
    // check it
    if (jsonInputs == null) {
        // empty down the collection
        _sessionVariables = null;
    } else {
        // initialise the collection
        _sessionVariables = new ArrayList<SessionVariable>();
        // loop it
        for (int i = 0; i < jsonInputs.length(); i++) {
            // get this input
            JSONObject jsonInput = jsonInputs.getJSONObject(i);
            // add it to the collection
            _sessionVariables.add(new SessionVariable(jsonInput.getString("name"),
                    jsonInput.getString("itemId"), jsonInput.optString("field")));
        }
    }
}

From source file:screenieup.MixtapeUpload.java

/**
 * Parse the response to get the image link.
 * @param response the image link resulting from the upload
 *//*  www .j a v  a2s. c  o m*/
private void parseResponse(String response) {
    JSONObject outerjson = new JSONObject(response);
    JSONArray jsnarray = (JSONArray) outerjson.get("files");
    JSONObject innerjson = (JSONObject) jsnarray.get(0);
    mixtapeurl = innerjson.get("url").toString();
}

From source file:org.apache.flume.sink.customhdfs.TestJson.java

public static void main(String[] args) throws JSONException {
    //log_time:long,hos_id:string,log_type:string,user_mac:string,supp_id:string
    Map<String, String> tableFieldsConf = (Map<String, String>) new ListOrderedMap();

    tableFieldsConf.put("log_typed", "string");
    tableFieldsConf.put("supp_id", "string");
    tableFieldsConf.put("hos_id", "string");
    tableFieldsConf.put("log_time", "string");
    tableFieldsConf.put("user_mac", "string");
    String eventBodyStr = "portal\t{\"log_time\":1111,\"hos_id\":222,\"log_type\":\"4\",\"user_mac\":\"dd:dfsfsdfsdfs\",\"supp_id\":\"3\"}";
    String[] bodyStrArray = eventBodyStr.split("\t");
    String dfrom = bodyStrArray[0];
    JSONObject obj = new JSONObject(bodyStrArray[1]);

    StringBuffer sbf = new StringBuffer(dfrom);
    for (Map.Entry<String, String> entry : tableFieldsConf.entrySet()) {
        sbf.append("\t");
        sbf.append(obj.get(entry.getKey()));
    }//from   w w w  .j av  a2  s.c  o  m

    System.out.println(sbf.toString());
}

From source file:com.hp.mqm.atrf.alm.services.AlmEntityService.java

private void handleExceptionFromALM(RuntimeException e) {
    String errorMsg;//w ww. ja  v  a  2  s  .  c o  m
    try {
        String msg = e.getMessage();
        JSONObject jsonObj = new JSONObject(msg);
        errorMsg = (String) jsonObj.get("Title");
    } catch (Exception parseEx) {
        throw e;
    }
    throw new AlmRestException(errorMsg);
}

From source file:com.hp.mqm.atrf.alm.services.AlmEntityService.java

private AlmEntityCollection parseCollection(String entitiesCollectionStr) {
    AlmEntityCollection coll = new AlmEntityCollection();
    JSONObject jsonObj = new JSONObject(entitiesCollectionStr);
    int total = jsonObj.getInt("TotalResults");
    coll.setTotal(total);//from  w  ww  .j av a  2  s. c o  m

    JSONArray entitiesJArr = jsonObj.getJSONArray("entities");
    for (int i = 0; i < entitiesJArr.length(); i++) {

        JSONObject entObj = entitiesJArr.getJSONObject(i);
        String type = entObj.getString("Type");

        AlmEntity almEntity = createEntity(type);

        JSONArray fieldsJArr = entObj.getJSONArray("Fields");
        for (int j = 0; j < fieldsJArr.length(); j++) {
            JSONObject fieldObj = fieldsJArr.getJSONObject(j);
            String name = fieldObj.getString("Name");
            JSONArray valuesArr = fieldObj.getJSONArray("values");
            boolean filled = false;
            if (valuesArr.length() > 0) {
                JSONObject valueObj = valuesArr.getJSONObject(0);
                if (valueObj.has("value")) {
                    Object value = valueObj.get("value");
                    almEntity.put(name, value);
                    filled = true;
                }
            }

            if (!filled) {
                //the field has no value - just set it with null value
                almEntity.put(name, null);
            }
        }

        //almEntity.put(AlmEntity.FIELD_URL, generateALMReferenceURL(almEntity));
        coll.getEntities().add(almEntity);
    }

    return coll;
}

From source file:com.hp.mqm.atrf.alm.services.AlmEntityService.java

private List<String> parseProjects(String projectsjson) {
    List<String> projectList = new ArrayList<>();
    JSONObject jsonObj = new JSONObject(projectsjson);

    JSONArray projectArr = null;//from w  w w .  jav a2 s. c o  m
    //single project
    if (jsonObj.has("Project")) {
        projectArr = (JSONArray) jsonObj.get("Project");
        ;
    } else {
        //several projects
        JSONObject projectsObj = (JSONObject) jsonObj.get("Projects");
        projectArr = (JSONArray) projectsObj.get("Project");

    }
    for (int i = 0; i < projectArr.length(); i++) {
        JSONObject entObj = projectArr.getJSONObject(i);
        String name = entObj.getString("Name");
        projectList.add(name);
    }

    return projectList;
}

From source file:org.kafka.event.microaggregator.core.MicroAggregationLoader.java

public void staticAggregation(String eventJson) {
    try {/*ww w. ja  v  a  2 s  . c  o m*/
        logger.info("Event Json:" + eventJson);
        JSONObject jsonObject = new JSONObject(eventJson);
        String startTime = null;
        String endTime = null;
        if (jsonObject.has("startTime")) {
            startTime = jsonObject.get("startTime") != null ? jsonObject.get("startTime").toString() : null;
        }
        if (jsonObject.has("endTime")) {
            endTime = jsonObject.get("endTime") != null ? jsonObject.get("endTime").toString() : null;
        }
        aggregationDAO.startStaticAggregation(startTime, endTime);
    } catch (Exception e) {
        logger.error("Exception:" + e);
    }
}

From source file:rsInstanceJumpstart.CloudServerPanelInstance.java

private boolean checkSuccessfulPowerOn() {
    String output = "";
    HttpURLConnection connection;
    String successCheckStatus = "";
    try {/*from   w w w .  ja v a 2  s.  c o m*/
        try {
            output = "";
            connection = (HttpURLConnection) new URL(serverLink).openConnection();

            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-Auth-Token", authToken);

            InputStream response;

            response = connection.getInputStream();

            //System.out.println(String.valueOf(connection.getResponseCode()));

            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(response));
                String line;
                while ((line = reader.readLine()) != null) {
                    output += line + "\n";
                }
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        System.out.println(e);
                    }
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
        JSONObject thisServer = new JSONObject(output);
        System.out.println(thisServer.getJSONObject("server").get("status").toString());
        successCheckStatus = thisServer.getJSONObject("server").get("status").toString();

    } catch (JSONException e) {
        //let's assume for now we won't have any
    }
    //System.out.println(output);
    if ("ACTIVE".equals(successCheckStatus)) {
        return true;
    } else {
        return false;
    }

}

From source file:com.util.finalProy.java

/**
 * @param args the command line arguments
 *//*  w  w  w .j a  va 2s  .  c om*/
public static void main(String[] args) throws JSONException {
    // TODO code application logic her
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    JSONArray dataJson = new JSONArray();
    dataJson = objJason.getJSONArray("data");

    System.out.println("objeto normal 1 " + dataJson.toString());
    //
    //
    System.out.println(
            "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
    String jsonString2 = dataJson.toString();
    String temp = dataJson.toString();
    temp = jsonString2.replace("[", "");
    jsonString2 = temp.replace("]", "");
    System.out.println("new json string" + jsonString2);

    JSONObject objJson2 = new JSONObject(jsonString2);
    System.out.println("el objeto simple json es " + objJson2.toString());

    System.out.println(
            "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");

    String account1 = objJson2.optString("account");
    System.out.println(account1);
    JSONObject objJson3 = new JSONObject(account1);
    System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
    System.out.println(
            "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
    String firstName = objJson3.getString("first_name");
    System.out.println(firstName);
    System.out.println(objJson3.get("id"));
    System.out.println(
            "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
    Gson gson = new Gson();
    Account account = gson.fromJson(objJson3.toString(), Account.class);
    System.out.println(account.getFirst_name());
    System.out.println(account.getCreation());
}