Example usage for org.json JSONObject length

List of usage examples for org.json JSONObject length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of keys stored in the JSONObject.

Usage

From source file:util.Overview.java

public static void getFlows(JSONObject Summary) throws JSONException, SQLException, IOException {
    /* /*from w ww.ja va2s  . co m*/
     * LOGICA PARA SACAR LA LISTA DE SWITCHES QUE CONTIENEN FLUJOS Y 
     * LOS FLUJOS INSTALADOS EN CADA SWITCH Y SUS VARIABLES PARA 
     * LA BASE DE DATOS
     */

    JSONArray AS = Summary.names(); // Arreglo de Switches conectados                                 

    for (int i = 0; i < Summary.length(); i++) {
        JSONObject s = Summary.getJSONObject(AS.getString(i)); // Se obtiene el JSONObject de los flujos que pertenece a cada switch
        JSONArray arr = s.names(); // Arreglo con los nombres de los flujos para ser recorrido

        for (int j = 0; j < s.length(); j++) {
            JSONObject t = s.getJSONObject(arr.getString(j)); // Se obtiene el JSONObject con los datos del flujo actual
            JSONObject match = t.getJSONObject("match"); // Se obtiene el JSONObject con los matchs del flujo actual
            int priority = t.getInt("priority"); // Se obtiene la prioridad del flujo actual
            int InputPort = match.getInt("inputPort"); // Se obtiene el inputPort del flujo actual
            JSONArray action = t.getJSONArray("actions"); // Se obtiene el JSONArray con los actions del flujo actual
            JSONObject actions = action.getJSONObject(0); // Se obtiene el JSONObject con el action del flujo actual
            int OutputPort = actions.getInt("port"); // Se obtiene el outputPort del flujo actual
            String accion = actions.getString("type"); // Se obtiene el tipo de la accion del flujo actual

            DBManager dbm = new DBManager();
            String sname = arr.getString(j);
            int switchh = dbm.getIndex(AS.getString(i));
            dbm.InsertFlow(j, i, sname, priority, InputPort, accion, OutputPort);
        }
    }
}

From source file:util.Overview.java

public static void getPortStatistics(JSONObject PortSummary) throws JSONException {
    JSONArray PortNames;//from   w  w w. j  a v  a 2 s.c om
    PortNames = PortSummary.names();

    for (int i = 0; i < PortSummary.length(); i++) {
        //se obtiene el arreglo que contiene las caracteristicas 
        //del swich actual
        JSONArray pri = PortSummary.getJSONArray(PortNames.getString(i));

        for (int j = 0; j < pri.length(); j++) {
            System.out.println("\n estadisticas generales del swich " + PortNames.getString(i));

            //se obtiene el objeto JSON con las estadisticas de cada puerto
            JSONObject pre = pri.getJSONObject(j);
            int portNumber, receiveBytes, collisions, transmitBytes;
            int transmitPackets, receivePackets;

            portNumber = pre.getInt("portNumber");
            receiveBytes = pre.getInt("receiveBytes");
            collisions = pre.getInt("collisions");
            transmitBytes = pre.getInt("transmitBytes");
            transmitPackets = pre.getInt("transmitPackets");
            receivePackets = pre.getInt("receivePackets");

            // SE DEBE VERIFICAR UNA VARIABLE 'DATE' PARA ENVIAR A LA BASE DE DATOS Y QUE SEA EL EJE X DE UNA POSIBLE GRAFICA
            //DBManager dbm = new DBManager();
            //String sname = arr.getString(j);              
            //int switchh = dbm.getIndex(AS.getString(i));
            //dbm.InsertPortStatistics(j,i,portNumber,receiveBytes,collisions,transmitBytes,transmitPackets,receivePackets);

            //System.out.println("portNumber: " + portNumber);
            //System.out.println("receiveBytes: " + receiveBytes);
            //System.out.println("collisions: " + collisions);
            //System.out.println("transmitBytes: " + transmitBytes);
            //System.out.println("transmitPackets: " + transmitPackets);
            //System.out.println("receivePackets: " + receivePackets);
        }
    }
}

From source file:org.archive.porky.JSON.java

/**
 * Convert JSON object into a Pig object, recursively convert
 * children as well.//  w w  w. ja v  a2  s . c o m
 */
public static Object fromJSON(Object o) throws IOException, JSONException {
    if (o instanceof String || o instanceof Long || o instanceof Double || o instanceof Integer) {
        return o;
    } else if (JSONObject.NULL.equals(o)) {
        return null;
    } else if (o instanceof JSONObject) {
        JSONObject json = (JSONObject) o;

        Map<String, Object> map = new HashMap<String, Object>(json.length());

        // If getNames() returns null, then it's  an empty JSON object.
        String[] names = JSONObject.getNames(json);

        if (names == null)
            return map;

        for (String key : JSONObject.getNames(json)) {
            Object value = json.get(key);

            // Recurse the value
            map.put(key, fromJSON(value));
        }

        // Now, check to see if the map keys match the formula for
        // a Tuple, that is if they are: "$0", "$1", "$2", ...

        // First, peek to see if there is a "$0" key, if so, then 
        // start moving the map entries into a Tuple.
        if (map.containsKey("$0")) {
            Tuple tuple = TupleFactory.getInstance().newTuple(map.size());

            for (int i = 0; i < map.size(); i++) {
                // If any of the expected $N keys is not found, give
                // up and return the map.
                if (!map.containsKey("$" + i))
                    return map;

                tuple.set(i, map.get("$" + i));
            }

            return tuple;
        }

        return map;
    } else if (o instanceof JSONArray) {
        JSONArray json = (JSONArray) o;

        List<Tuple> tuples = new ArrayList<Tuple>(json.length());

        for (int i = 0; i < json.length(); i++) {
            tuples.add(TupleFactory.getInstance().newTuple(fromJSON(json.get(i))));
        }

        DataBag bag = BagFactory.getInstance().newDefaultBag(tuples);

        return bag;
    } else if (o instanceof Boolean) {
        // Since Pig doesn't have a true boolean data type, we map it to
        // String values "true" and "false".
        if (((Boolean) o).booleanValue()) {
            return "true";
        }
        return "false";
    } else {
        // FIXME: What to do here?
        throw new IOException("Unknown data-type serializing from JSON: " + o);
    }
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

public static JSONObject removeNamespacesFromOGJsonObject(JSONObject jsonObject, boolean requireNamespace) {
    if (jsonObject == null) {
        return null;
    }/*w w w .j av a 2 s  .  c  om*/

    try {
        JSONObject newJsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        JSONArray names = jsonObject.names();
        for (int i = 0; i < names.length(); ++i) {
            String key = names.getString(i);
            Object value = null;
            value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                value = removeNamespacesFromOGJsonObject((JSONObject) value, true);
            } else if (value instanceof JSONArray) {
                value = removeNamespacesFromOGJsonArray((JSONArray) value, true);
            }

            Pair<String, String> fieldNameAndNamespace = getFieldNameAndNamespaceFromFullName(key);
            String namespace = fieldNameAndNamespace.first;
            String fieldName = fieldNameAndNamespace.second;

            if (requireNamespace) {
                if (namespace != null && namespace.equals("fbsdk")) {
                    newJsonObject.put(key, value);
                } else if (namespace == null || namespace.equals("og")) {
                    newJsonObject.put(fieldName, value);
                } else {
                    data.put(fieldName, value);
                }
            } else if (namespace != null && namespace.equals("fb")) {
                newJsonObject.put(key, value);
            } else {
                newJsonObject.put(fieldName, value);
            }
        }

        if (data.length() > 0) {
            newJsonObject.put("data", data);
        }

        return newJsonObject;
    } catch (JSONException e) {
        throw new FacebookException("Failed to create json object from share content");
    }
}

From source file:org.everit.json.schema.ObjectSchema.java

private void testSize(final JSONObject subject) {
    int actualSize = subject.length();
    if (minProperties != null && actualSize < minProperties.intValue()) {
        throw new ValidationException(
                String.format("minimum size: [%d], found: [%d]", minProperties, actualSize));
    }//from w  w  w .j a v a2s  . c  o m
    if (maxProperties != null && actualSize > maxProperties.intValue()) {
        throw new ValidationException(
                String.format("maximum size: [%d], found: [%d]", maxProperties, actualSize));
    }
}

From source file:com.microsoft.live.unittest.UploadTest.java

@Override
protected void checkValidResponseBody(LiveOperation operation) throws Exception {
    JSONObject result = operation.getResult();

    assertEquals(2, result.length());

    String id = result.getString(JsonKeys.ID);
    assertEquals(FILE_ID, id);//from   w  w  w .ja va 2 s.  c o m

    String source = result.getString(JsonKeys.SOURCE);
    assertEquals(SOURCE, source);
}

From source file:com.mparticle.internal.ConfigManager.java

public void setIntegrationAttributes(int kitId, Map<String, String> newAttributes) {
    try {/*from w  w w.  j a v  a 2  s  . c o m*/
        JSONObject newJsonAttributes = null;
        if (newAttributes != null && !newAttributes.isEmpty()) {
            newJsonAttributes = new JSONObject();
            for (Map.Entry<String, String> entry : newAttributes.entrySet()) {
                newJsonAttributes.put(entry.getKey(), entry.getValue());
            }
        }
        JSONObject currentJsonAttributes = getIntegrationAttributes();
        if (currentJsonAttributes == null) {
            currentJsonAttributes = new JSONObject();
        }
        currentJsonAttributes.put(Integer.toString(kitId), newJsonAttributes);
        if (currentJsonAttributes.length() > 0) {
            mPreferences.edit()
                    .putString(Constants.PrefKeys.INTEGRATION_ATTRIBUTES, currentJsonAttributes.toString())
                    .apply();
        } else {
            mPreferences.edit().remove(Constants.PrefKeys.INTEGRATION_ATTRIBUTES).apply();
        }
    } catch (JSONException jse) {

    }
}

From source file:com.rjfun.cordova.qq.QQPlugin.java

@Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
    PluginResult result = null;/*w  w  w  .  j av a 2 s.  co  m*/

    if (ACTION_SET_OPTIONS.equals(action)) {
        JSONObject options = inputs.optJSONObject(0);
        this.setOptions(options);
        result = new PluginResult(Status.OK);

    } else if (ACTION_SHARE.equals(action)) {
        JSONObject options = inputs.optJSONObject(0);
        if (options.length() > 1) {
            this.setOptions(options);
        }
        boolean isOk = this.share(options);

        // we send callback in qq callback
        currentCallbackContext = callbackContext;
        return true;

    } else {
        Log.w(LOGTAG, String.format("Invalid action passed: %s", action));
        result = new PluginResult(Status.INVALID_ACTION);
    }

    if (result != null)
        sendPluginResult(result, callbackContext);

    return true;
}

From source file:com.qbcps.sifterclient.SifterReader.java

private String getFilterSlug() {
    String projDetailURL;/*from   ww  w  .  j  a v a2  s  . co m*/
    int issuesPerPage;
    JSONArray status;
    JSONArray priority;
    int numStatuses;
    int numPriorities;
    boolean[] filterStatus;
    boolean[] filterPriority;
    try {
        JSONObject filters = mSifterHelper.getFiltersFile();
        if (filters.length() == 0)
            return "";
        issuesPerPage = filters.getInt(IssuesActivity.PER_PAGE);
        status = filters.getJSONArray(IssuesActivity.STATUS);
        priority = filters.getJSONArray(IssuesActivity.PRIORITY);
        numStatuses = status.length();
        numPriorities = priority.length();
        filterStatus = new boolean[numStatuses];
        filterPriority = new boolean[numPriorities];
        for (int i = 0; i < numStatuses; i++)
            filterStatus[i] = status.getBoolean(i);
        for (int i = 0; i < numPriorities; i++)
            filterPriority[i] = priority.getBoolean(i);
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    projDetailURL = "?" + IssuesActivity.PER_PAGE + "=" + issuesPerPage;
    projDetailURL += "&" + IssuesActivity.GOTO_PAGE + "=1";
    JSONObject statuses;
    JSONObject priorities;
    JSONArray statusNames;
    JSONArray priorityNames;
    try {
        JSONObject sifterJSONObject = mSifterHelper.getSifterFilters();
        statuses = sifterJSONObject.getJSONObject(IssuesActivity.STATUSES);
        priorities = sifterJSONObject.getJSONObject(IssuesActivity.PRIORITIES);
        statusNames = statuses.names();
        priorityNames = priorities.names();
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    try {
        String filterSlug = "&s=";
        for (int i = 0; i < numStatuses; i++) {
            if (filterStatus[i])
                filterSlug += String.valueOf(statuses.getInt(statusNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
        filterSlug = "&p=";
        for (int i = 0; i < numPriorities; i++) {
            if (filterPriority[i])
                filterSlug += String.valueOf(priorities.getInt(priorityNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
    } catch (JSONException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    return projDetailURL;
}

From source file:com.datasnap.android.info.test.InfoManagerTest.java

@Test
public void testGet() {
    InfoManager manager = new InfoManager(new Config());
    JSONObject object = manager.build(this.getContext());
    assertThat(object.length()).isGreaterThan(0);
}