Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

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

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

From source file:com.norman0406.slimgress.API.Knobs.PortalModSharedKnobs.java

public PortalModSharedKnobs(JSONObject json) throws JSONException {
    super(json);/*from w ww  . j ava  2 s  .co  m*/

    mMultiTurretFreqDiminishingValues = getIntArray(json, "multiTurretFreqDiminishingValues");
    mMultiForceAmpDiminishingValues = getIntArray(json, "multiForceAmpDiminishingValues");
    mMultiLinkAmpDiminishingValues = getIntArray(json, "multiLinkAmpDiminishingValues");

    mDiminishingValues = new HashMap<String, List<Integer>>();
    JSONObject diminishingValues = json.getJSONObject("diminishingValues");
    Iterator<?> it = diminishingValues.keys();
    while (it.hasNext()) {
        String key = (String) it.next();
        mDiminishingValues.put(key, getIntArray(diminishingValues, key));
    }
}

From source file:org.uiautomation.ios.UIAModels.predicate.AbstractCriteria.java

@SuppressWarnings("unchecked")
public static <T extends Criteria> T parse(JSONObject serialized, CriteriaDecorator decorator) {
    try {//w w  w  .  ja va 2 s . co m
        int nbKeys = serialized.length();
        switch (nbKeys) {
        case KEYS_IN_EMPTY_CRITERIA:
            return (T) new EmptyCriteria();
        case KEYS_IN_COMPOSED_CRITERIA:
            String key = (String) serialized.keys().next();
            CompositionType type = CompositionType.valueOf(key);
            return (T) buildComposedCriteria(serialized, type, decorator);
        case KEYS_IN_LOCATION_CRITERIA:
            int x = serialized.getInt("x");
            int y = serialized.getInt("y");
            return (T) buildLocationCriteria(serialized, x, y, decorator);
        case KEYS_IN_PROPERTY_CRITERIA:
            String method = serialized.getString("method");
            String tmp = method.substring(0, 1).toUpperCase() + method.toLowerCase().substring(1) + "Criteria";
            String clazz = AbstractCriteria.class.getPackage().getName() + "." + tmp;
            Class<? extends PropertyEqualCriteria> c = (Class<? extends PropertyEqualCriteria>) Class
                    .forName(clazz);
            return (T) buildPropertyBaseCriteria(serialized, c, decorator);
        default:
            throw new InvalidSelectorException("can't find the type : " + serialized.toString());
        }
    } catch (Exception e) {
        throw new WebDriverException(e);
    }

}

From source file:com.rainmakerlabs.bleepsample.BleepService.java

private Intent createIntent(String intentAction, String intentUri, String intentType, String intentExtras) {
    Intent launchIntent;//from   ww  w. j  av a  2 s . com
    if (intentUri.equalsIgnoreCase("")) {
        launchIntent = getPackageManager().getLaunchIntentForPackage(intentAction);
        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    } else {
        launchIntent = new Intent(intentAction, Uri.parse(intentUri));
    }
    if (!intentType.equalsIgnoreCase(""))
        launchIntent.setType(intentType);
    if (!intentExtras.equalsIgnoreCase("")) {
        try {
            JSONObject intentExtrasDict = new JSONObject(intentExtras);
            Iterator<?> keys = intentExtrasDict.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                launchIntent.putExtra(key, intentExtrasDict.get(key).toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return launchIntent;
}

From source file:com.example.jumpnote.android.jsonrpc.JsonRpcJavaClient.java

public void callBatch(final List<JsonRpcClient.Call> calls, final JsonRpcClient.BatchCallback callback) {
    HttpPost httpPost = new HttpPost(mRpcUrl);
    JSONObject requestJson = new JSONObject();
    JSONArray callsJson = new JSONArray();
    try {//from w  w w.j a  v  a  2s  . c o  m
        for (int i = 0; i < calls.size(); i++) {
            JsonRpcClient.Call call = calls.get(i);

            JSONObject callJson = new JSONObject();

            callJson.put("method", call.getMethodName());

            if (call.getParams() != null) {
                JSONObject callParams = (JSONObject) call.getParams();
                @SuppressWarnings("unchecked")
                Iterator<String> keysIterator = callParams.keys();
                String key;
                while (keysIterator.hasNext()) {
                    key = keysIterator.next();
                    callJson.put(key, callParams.get(key));
                }
            }

            callsJson.put(i, callJson);
        }

        requestJson.put("calls", callsJson);
        httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8"));
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "POST request: " + requestJson.toString());
        }
    } catch (JSONException e) {
        // throw e;
    } catch (UnsupportedEncodingException e) {
        // throw e;
    }

    try {
        HttpResponse httpResponse = mHttpClient.execute(httpPost);
        final int responseStatusCode = httpResponse.getStatusLine().getStatusCode();
        if (200 <= responseStatusCode && responseStatusCode < 300) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "POST response: " + sb.toString());
            }
            JSONTokener tokener = new JSONTokener(sb.toString());
            JSONObject responseJson = new JSONObject(tokener);
            JSONArray resultsJson = responseJson.getJSONArray("results");
            Object[] resultData = new Object[calls.size()];

            for (int i = 0; i < calls.size(); i++) {
                JSONObject result = resultsJson.getJSONObject(i);
                if (result.has("error")) {
                    callback.onError(i, new JsonRpcException((int) result.getInt("error"),
                            calls.get(i).getMethodName(), result.getString("message"), null));
                    resultData[i] = null;
                } else {
                    resultData[i] = result.get("data");
                }
            }

            callback.onData(resultData);
        } else {
            callback.onError(-1, new JsonRpcException(-1, "Received HTTP status code other than HTTP 2xx: "
                    + httpResponse.getStatusLine().getReasonPhrase()));
        }
    } catch (IOException e) {
        Log.e("JsonRpcJavaClient", e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e("JsonRpcJavaClient", "Error parsing server JSON response: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.hypertopic.RESTDatabase.java

/**
 * @return {key0:{key1:{attribute0:[value0, value1]}}}
 * for {rows:[ //www  .  j a  v a2  s.c o m
 *   {key:[key0, key1], value:{attribute0:value0}},
 *   {key:[key0, key1], value:{attribute0:value1}}
 * ]}
 */
protected static JSONObject index(JSONObject view) throws Exception {
    JSONObject result = new JSONObject();
    JSONArray rows = view.getJSONArray("rows");
    for (int i = 0; i < rows.length(); i++) {
        JSONObject r = rows.getJSONObject(i);
        JSONArray keys = r.getJSONArray("key");
        JSONObject current = result;
        for (int k = 0; k < keys.length(); k++) {
            current = current.getJSONObjectOrCreate(keys.getString(k));
        }
        JSONObject value = r.getJSONObject("value");
        Iterator<String> v = value.keys();
        while (v.hasNext()) {
            String attribute = v.next();
            current.justAccumulate(attribute, value.get(attribute));
        }
    }
    return result;
}

From source file:com.pivotal.gemfire.tools.pulse.internal.controllers.PulseController.java

@RequestMapping(value = "/pulseUpdate", method = RequestMethod.POST)
public void getPulseUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String pulseData = request.getParameter("pulseData");

    JSONObject responseMap = new JSONObject();

    JSONObject requestMap = null;

    try {/* ww w.j a  va2 s.  co  m*/
        requestMap = new JSONObject(pulseData);
        Iterator<?> keys = requestMap.keys();

        // Execute Services
        while (keys.hasNext()) {
            String serviceName = keys.next().toString();
            try {
                PulseService pulseService = pulseServiceFactory.getPulseServiceInstance(serviceName);
                responseMap.put(serviceName, pulseService.execute(request));
            } catch (Exception serviceException) {
                LOGGER.warning("serviceException = " + serviceException.getMessage());
                responseMap.put(serviceName, NoDataJSON);
            }
        }

    } catch (JSONException eJSON) {
        LOGGER.logJSONError(new JSONException(eJSON),
                new String[] { "requestMap:" + ((requestMap == null) ? "" : requestMap) });
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }

    // Create Response
    response.getOutputStream().write(responseMap.toString().getBytes());
}

From source file:com.muzima.service.HTMLFormObservationCreator.java

private List<Observation> extractObservationFromJSONObject(JSONObject jsonObject)
        throws JSONException, ConceptController.ConceptFetchException, ConceptController.ConceptSaveException {
    List<Observation> observations = new ArrayList<Observation>();
    Iterator keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        observations.addAll(extractBasedOnType(jsonObject, key));
    }//from  w  w w  .ja  v a  2s  .co m
    observations.removeAll(Collections.singleton(null));
    return observations;
}

From source file:org.odk.collect.android.tasks.FormLoaderTask.java

private void populateWithInitialData(FormController fc, String initialData) {
    try {/* w  w  w .  j  av  a2s  .  c  o  m*/
        JSONObject o = new JSONObject(initialData);

        if (o != null) {
            for (Iterator<String> iter = o.keys(); iter.hasNext();) {
                String key = iter.next();
                String v = o.get(key).toString();
                String s2 = String.format("%s=%s", key, v);
                Log.d("flikk", s2);

                String xPath = String.format("question./data/%s[1]", key);

                try {
                    FormIndex fi = fc.getIndexFromXPath(xPath);
                    if (fi != null) {
                        fc.saveAnswer(fi, ExternalAppsUtils.asStringData(v));
                    }
                } catch (JavaRosaException e) {
                    e.printStackTrace();
                }

            }
        }

    } catch (JSONException ex) {

    }
}

From source file:uk.ac.imperial.presage2.web.SimulationServlet.java

/**
 * REST CREATE simulation/*from ww w . jav  a  2  s .co  m*/
 */
@Override
protected synchronized void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    logRequest(req);
    try {
        // parse posted simulation json object
        JSONObject request = new JSONObject(new JSONTokener(req.getReader()));
        // validate data
        String name = request.getString("name");
        String classname = request.getString("classname");
        String state = request.getString("state");
        int finishTime = request.getInt("finishTime");
        PersistentSimulation sim = sto.createSimulation(name, classname, state, finishTime);
        resp.setStatus(201);
        if (!state.equalsIgnoreCase("GROUP")) {
            // add finishTime as a parameter
            sim.addParameter("finishTime", Integer.toString(finishTime));
        }
        if (request.has("parameters")) {
            JSONObject parameters = request.getJSONObject("parameters");
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = parameters.keys(); iterator.hasNext();) {
                String key = (String) iterator.next();
                sim.addParameter(key, parameters.getString(key));
            }
        }
        // set simulation parent
        if (request.has("parent")) {
            try {
                long parentId = request.getLong("parent");
                PersistentSimulation parent = sto.getSimulationById(parentId);
                if (parent != null)
                    sim.setParentSimulation(parent);
            } catch (JSONException e) {
                // ignore non number parent.
            }
        }

        // clear sim cache
        this.cachedSimulations = null;

        // return created simulation object
        JSONObject response = new JSONObject();
        response.put("success", true);
        response.put("message", "Created simulation");
        response.put("data", simulationToJSON(sim));
        resp.getWriter().write(response.toString());
    } catch (JSONException e) {
        // bad request
        resp.setStatus(400);
        logger.warn("Couldn't create new simulation", e);
    }
}

From source file:uk.ac.imperial.presage2.web.SimulationServlet.java

/**
 * REST UPDATE simulation/* w w w.jav a2  s.  c  om*/
 */
@Override
protected synchronized void doPut(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    logRequest(req);
    String path = req.getPathInfo();
    Matcher matcher = ID_REGEX.matcher(path);
    if (matcher.matches()) {
        long simId = Integer.parseInt(matcher.group(1));
        try {
            // get data sent to us
            JSONObject input = new JSONObject(new JSONTokener(req.getReader()));
            // validate fields
            if (Integer.parseInt(input.get("id").toString()) != simId || input.getString("state").length() < 1
                    || input.getInt("currentTime") < 0 || input.getInt("finishTime") < 0) {
                resp.setStatus(400);
                return;
            }

            PersistentSimulation sim = sto.getSimulationById(simId);
            String state = input.getString("state");
            if (!(sim.getState().equals(state))) {
                sim.setState(state);
            }
            int currentTime = input.getInt("currentTime");
            if (!(sim.getCurrentTime() == currentTime)) {
                sim.setCurrentTime(currentTime);
            }
            int finishTime = input.getInt("finishTime");
            if (!(sim.getFinishTime() == finishTime)) {
                sim.setCurrentTime(finishTime);
            }
            JSONObject parameters = input.getJSONObject("parameters");
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = parameters.keys(); iterator.hasNext();) {
                String key = (String) iterator.next();
                sim.addParameter(key, parameters.getString(key));
            }
            // parent simulation
            try {
                long parentId = input.getLong("parent");
                PersistentSimulation parent = sim.getParentSimulation();
                if (parentId == 0 && parent != null) {
                    sim.setParentSimulation(null);
                } else if (parentId > 0 && parent.getID() != parentId) {
                    parent = sto.getSimulationById(parentId);
                    if (parent != null) {
                        sim.setParentSimulation(parent);
                    }
                }
            } catch (JSONException e) {
            }

            JSONObject response = new JSONObject();
            response.put("success", true);
            response.put("data", simulationToJSON(sim));
            resp.getWriter().write(response.toString());
            // clear sim cache
            this.cachedSimulations = null;
        } catch (JSONException e) {
            resp.setStatus(400);
        }
    } else {
        resp.setStatus(400);
    }
}