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:com.github.cambierr.lorawanpacket.semtech.PullResp.java

public PullResp(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PULL_RESP);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 1) {
        throw new MalformedPacketException("too short");
    }//from   w  ww. j av a  2s.  c  om

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    txpks = new ArrayList<>();

    if (!jo.has("txpk")) {
        throw new MalformedPacketException("missing json (txpk)");
    }

    if (!jo.get("txpk").getClass().equals(JSONArray.class)) {
        throw new MalformedPacketException("malformed json (txpk)");
    }
    JSONArray rxpk = jo.getJSONArray("txpk");

    for (int i = 0; i < rxpk.length(); i++) {
        txpks.add(new Txpk(rxpk.getJSONObject(i)));
    }
}

From source file:org.wso2.emm.agent.services.MessageProcessor.java

/**
 * Call the message retrieval end point of the server to get messages pending.
 */// w  ww  .  ja  va  2  s  .  c o  m
public void getMessages() throws AndroidAgentException {
    String ipSaved = Constants.DEFAULT_HOST;
    String prefIP = Preference.getString(context.getApplicationContext(), Constants.PreferenceFlag.IP);
    if (prefIP != null) {
        ipSaved = prefIP;
    }
    ServerConfig utils = new ServerConfig();
    utils.setServerIP(ipSaved);
    String url = utils.getAPIServerURL(context) + Constants.DEVICES_ENDPOINT + deviceId
            + Constants.NOTIFICATION_ENDPOINT;

    Log.i(TAG, "Get pending operations from: " + url);

    String requestParams;
    ObjectMapper mapper = new ObjectMapper();
    try {
        requestParams = mapper.writeValueAsString(replyPayload);
        if (replyPayload != null) {
            for (org.wso2.emm.agent.beans.Operation operation : replyPayload) {
                if (operation.getCode().equals(Constants.Operation.WIPE_DATA)
                        && !operation.getStatus().equals(ERROR_STATE)) {
                    isWipeTriggered = true;
                } else if (operation.getCode().equals(Constants.Operation.REBOOT)
                        && !operation.getStatus().equals(ERROR_STATE)) {
                    isRebootTriggered = true;
                } else if (operation.getCode().equals(Constants.Operation.UPGRADE_FIRMWARE)
                        && !operation.getStatus().equals(ERROR_STATE)) {
                    isUpgradeTriggered = true;
                    Preference.putInt(context, "firmwareOperationId", operation.getId());
                } else if (operation.getCode().equals(Constants.Operation.EXECUTE_SHELL_COMMAND)
                        && !operation.getStatus().equals(ERROR_STATE)) {
                    isShellCommandTriggered = true;
                    try {
                        JSONObject payload = new JSONObject(operation.getPayLoad().toString());
                        shellCommand = (String) payload
                                .get(context.getResources().getString(R.string.shared_pref_command));
                    } catch (JSONException e) {
                        throw new AndroidAgentException("Invalid JSON format.", e);
                    }
                }
            }
        }
        String firmwareOperationMessage = Preference.getString(context,
                context.getResources().getString(R.string.firmware_upgrade_failed_message));
        int firmwareOperationId = Preference.getInt(context,
                context.getResources().getString(R.string.firmware_upgrade_failed_id));
        if (firmwareOperationMessage != null && firmwareOperationId != 0) {
            org.wso2.emm.agent.beans.Operation firmwareOperation = new org.wso2.emm.agent.beans.Operation();
            firmwareOperation.setId(firmwareOperationId);
            firmwareOperation.setCode(Constants.Operation.UPGRADE_FIRMWARE);
            firmwareOperation.setStatus(context.getResources().getString(R.string.operation_value_error));
            firmwareOperation.setOperationResponse(firmwareOperationMessage);
            if (replyPayload != null) {
                replyPayload.add(firmwareOperation);
            } else {
                replyPayload = new ArrayList<>();
                replyPayload.add(firmwareOperation);
            }
            Preference.putString(context,
                    context.getResources().getString(R.string.firmware_upgrade_failed_message), null);
        }

        int applicationOperationId = Preference.getInt(context,
                context.getResources().getString(R.string.app_install_id));
        String applicationOperationCode = Preference.getString(context,
                context.getResources().getString(R.string.app_install_code));
        String applicationOperationStatus = Preference.getString(context,
                context.getResources().getString(R.string.app_install_status));
        String applicationOperationMessage = Preference.getString(context,
                context.getResources().getString(R.string.app_install_failed_message));
        if (applicationOperationStatus != null && applicationOperationId != 0
                && applicationOperationCode != null) {
            Operation applicationOperation = new Operation();
            ApplicationManager appMgt = new ApplicationManager(context);
            applicationOperation.setId(applicationOperationId);
            applicationOperation.setCode(applicationOperationCode);
            applicationOperation = appMgt.getApplicationInstallationStatus(applicationOperation,
                    applicationOperationStatus, applicationOperationMessage);
            if (replyPayload == null) {
                replyPayload = new ArrayList<>();
            }
            replyPayload.add(applicationOperation);
            Preference.putString(context, context.getResources().getString(R.string.app_install_status), null);
            Preference.putString(context, context.getResources().getString(R.string.app_install_failed_message),
                    null);
            if (context.getResources().getString(R.string.operation_value_error)
                    .equals(applicationOperation.getStatus())
                    || context.getResources().getString(R.string.operation_value_completed)
                            .equals(applicationOperation.getStatus())) {
                Preference.putInt(context, context.getResources().getString(R.string.app_install_id), 0);
                Preference.putString(context, context.getResources().getString(R.string.app_install_code),
                        null);
                startPendingInstallation();
            }
        } else {
            startPendingInstallation();
        }

        if (Preference.hasPreferenceKey(context, Constants.Operation.LOGCAT)) {
            if (Preference.hasPreferenceKey(context, Constants.Operation.LOGCAT)) {
                Gson operationGson = new Gson();
                Operation logcatOperation = operationGson
                        .fromJson(Preference.getString(context, Constants.Operation.LOGCAT), Operation.class);
                if (replyPayload == null) {
                    replyPayload = new ArrayList<>();
                }
                replyPayload.add(logcatOperation);
                Preference.removePreference(context, Constants.Operation.LOGCAT);
            }
        }
        requestParams = mapper.writeValueAsString(replyPayload);
    } catch (JsonMappingException e) {
        throw new AndroidAgentException("Issue in json mapping", e);
    } catch (JsonGenerationException e) {
        throw new AndroidAgentException("Issue in json generation", e);
    } catch (IOException e) {
        throw new AndroidAgentException("Issue in parsing stream", e);
    }
    if (Constants.DEBUG_MODE_ENABLED) {
        Log.d(TAG, "Reply Payload: " + requestParams);
    }

    if (requestParams != null
            && requestParams.trim().equals(context.getResources().getString(R.string.operation_value_null))) {
        requestParams = null;
    }

    if (ipSaved != null && !ipSaved.isEmpty()) {
        CommonUtils.callSecuredAPI(context, url, HTTP_METHODS.PUT, requestParams, MessageProcessor.this,
                Constants.NOTIFICATION_REQUEST_CODE);
    } else {
        Log.e(TAG, "There is no valid IP to contact the server");
    }
}

From source file:to.sparks.mtgox.service.WebsocketClientService.java

@Override
public void onApplicationEvent(PacketEvent event) {
    JSONObject op = (JSONObject) event.getPayload();

    try {/*from  www . j  a v a 2 s.  c  om*/
        // logger.fine(aPacket.getUTF8());

        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper();

        //                    JsonParser jp = factory.createJsonParser(aPacket.getUTF8());
        //                    DynaBean op = mapper.readValue(jp, DynaBean.class);

        if (op.get("op") != null && op.get("op").equals("private")) {
            String messageType = op.get("private").toString();
            if (messageType.equalsIgnoreCase("ticker")) {
                OpPrivateTicker opPrivateTicker = mapper.readValue(factory.createJsonParser(op.toString()),
                        OpPrivateTicker.class);
                Ticker ticker = opPrivateTicker.getTicker();
                tickerEvent(ticker);
                logger.log(Level.FINE, "Ticker: last: {0}", new Object[] { ticker.getLast().toPlainString() });
            } else if (messageType.equalsIgnoreCase("depth")) {
                OpPrivateDepth opPrivateDepth = mapper.readValue(factory.createJsonParser(op.toString()),
                        OpPrivateDepth.class);
                Depth depth = opPrivateDepth.getDepth();
                depthEvent(depth);
                logger.log(Level.FINE, "Depth total volume: {0}",
                        new Object[] { depth.getTotalVolume().toPlainString() });
            } else if (messageType.equalsIgnoreCase("trade")) {
                OpPrivateTrade opPrivateTrade = mapper.readValue(factory.createJsonParser(op.toString()),
                        OpPrivateTrade.class);
                Trade trade = opPrivateTrade.getTrade();
                tradeEvent(trade);
                logger.log(Level.FINE, "Trade currency: {0}", new Object[] { trade.getPrice_currency() });
            } else {
                logger.log(Level.WARNING, "Unknown private operation: {0}", new Object[] { op.toString() });
            }

            // logger.log(Level.INFO, "messageType: {0}, payload: {1}", new Object[]{messageType, dataPayload});
        } else {
            logger.log(Level.WARNING, "Unknown operation: {0}, payload: {1}",
                    new Object[] { op.get("op"), op.toString() });
            // TODO:  Process the following types
            // subscribe
            // unsubscribe
            // remark
            // result
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
    }

}

From source file:com.joyfulmongo.db.ContainerObjectPointer.java

public void replaceObject(JFMongoObject refereeObject) {
    mObj.put(ContainerObjectFactory.TypeProps.__type.toString(),
            ContainerObjectFactory.TypeType.Object.toString());
    mObj.remove(Props.objectId.toString());
    JSONObject theObj = refereeObject.toJson();
    Iterator<String> keys = theObj.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        mObj.put(key, theObj.get(key));
    }/*from w w  w  . j a  va  2s  .  c  o m*/
}

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) {
    Object param = null;//from   www.ja v a 2s .  c o m
    Throwable ex = null;
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        if (m.getName().equals(name)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            if (paramTypes.length == 1 && jo.has(key)) {
                Class<?> tparam = paramTypes[0];
                boolean allowNull = false;
                try {
                    if (jo.isNull(key)) {
                        // do nothing because param is already null : lets us not null on other types
                    } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) {
                        param = new Long(jo.getLong(key));
                    } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) {
                        param = new Double(jo.getDouble(key));
                    } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) {
                        param = new Integer(jo.getInt(key));
                    } else if (String.class.isAssignableFrom(tparam)) {
                        param = jo.getString(key);
                    } else if (Enum.class.isAssignableFrom(tparam)) {
                        param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key));
                    } else if (Boolean.class.isAssignableFrom(tparam)) {
                        param = new Boolean(jo.getBoolean(key));
                    } else if (jo.isNull(key)) {
                        param = null;
                        allowNull = true;
                    } else if (Collection.class.isAssignableFrom(tparam)) {

                        if (m.getGenericParameterTypes().length > 0) {
                            Type t = m.getGenericParameterTypes()[0];
                            if (t instanceof ParameterizedType) {
                                ParameterizedType tv = (ParameterizedType) t;
                                if (tv.getActualTypeArguments().length > 0
                                        && tv.getActualTypeArguments()[0] == String.class) {

                                    List<String> ls = new ArrayList<String>();
                                    JSONArray ja = jo.optJSONArray(key);
                                    if (ja != null) {
                                        for (int j = 0; j < ja.length(); j++) {
                                            ls.add(ja.getString(j));
                                        }
                                    }
                                    param = ls;
                                } else if (tv.getActualTypeArguments().length == 1) {
                                    ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0];
                                    Class itemClass = (Class) type.getRawType();
                                    if (itemClass == Map.class && type.getActualTypeArguments().length == 2
                                            && type.getActualTypeArguments()[0] == String.class
                                            && type.getActualTypeArguments()[1] == Object.class) {

                                        List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

                                        JSONArray ja = jo.optJSONArray(key);
                                        if (ja != null) {
                                            for (int j = 0; j < ja.length(); j++) {
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                JSONObject mo = ja.getJSONObject(j);
                                                Iterator<String> keys = mo.keys();
                                                while (keys.hasNext()) {
                                                    String okey = keys.next();
                                                    Object ovalue = null;
                                                    // make sure we don't get JSONObject$Null
                                                    if (!mo.isNull(okey)) {
                                                        ovalue = mo.get(okey);
                                                    }
                                                    map.put(okey, ovalue);
                                                }
                                                ls.add(map);
                                            }
                                        }
                                        param = ls;
                                    } else {
                                        getLogger().warning(
                                                "Don't know how to handle Collection of type : " + itemClass);
                                    }

                                } else {
                                    getLogger().warning("Don't know how to handle Collection of type : "
                                            + tv.getActualTypeArguments()[0]);
                                }
                            }
                        }
                    } else {
                        getLogger().warning(
                                "Unable to serialize " + key + " :  Don't know how to handle " + tparam);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (param != null || allowNull) {

                    try {

                        if (m != null) {
                            Object[] args = { param };
                            m.invoke(targetObject, args);
                            ex = null;
                            break;
                        }
                    } catch (SecurityException e) {
                        ex = e;
                    } catch (IllegalArgumentException e) {
                        ex = e;
                    } catch (IllegalAccessException e) {
                        ex = e;
                    } catch (InvocationTargetException e) {
                        ex = e;
                    }
                }
            }
        }
    }
    if (ex != null) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException(ex);
        }
    }
}

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
private Object genericDeserialize(Object o, Object targetObject, String key) throws JSONException {

    if (o instanceof JSONObject) {
        JSONObject jo = (JSONObject) o;
        Map<String, Object> jaoo = new HashMap<String, Object>();

        // only add if we are not top level
        if (targetObject != null) {
            addValue(targetObject, jaoo, key);
        }//from   www  .j  ava2 s.  c o m
        Iterator<String> it = jo.keys();

        while (it.hasNext()) {
            String k = it.next();
            Object value = jo.get(k);
            genericDeserialize(value, jaoo, k);
        }
        // if we are the top level object return self
        if (targetObject == null) {
            return jaoo;
        }

    } else if (o instanceof JSONArray) {

        JSONArray ja = (JSONArray) o;

        List<Object> jal = new ArrayList<Object>();

        // only add if we are not top level
        if (targetObject != null) {
            addValue(targetObject, jal, key);
        }
        for (int i = 0; i < ja.length(); i++) {
            Object jao = ja.get(i);
            genericDeserialize(jao, jal, null);
        }
        // if we are the top level object return self
        if (targetObject == null) {
            return jal;
        }
        // primitives
    } else if (o instanceof Date) {
        Object value = ((Date) o).getTime();
        addValue(targetObject, value, key);
    } else {
        addValue(targetObject, o, key);
    }
    return null;
}

From source file:com.clevertrail.mobile.findtrail.Activity_FindTrail_ByLocation.java

public Point getLatLong(JSONObject jsonObject) {

    Double lon = new Double(0);
    Double lat = new Double(0);

    try {//w  ww. ja v  a  2 s  . c  o  m
        String sStatus = ((String) jsonObject.get("status"));
        if (sStatus.compareTo("OK") != 0)
            return null;

        //look into the json for the lat/long
        lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
                .getJSONObject("location").getDouble("lng");

        lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
                .getJSONObject("location").getDouble("lat");

    } catch (Exception e) {
        e.printStackTrace();
        return null;

    }

    return new Point(lat, lon);
}

From source file:com.skubit.bitid.fragments.SignInResponseFragment.java

private String getMessageValue(String message) {
    if (TextUtils.isEmpty(message)) {
        return null;
    }//from   w  ww  .j a  v  a2 s  . c  o m

    try {
        JSONObject joMessage = new JSONObject(message);
        if (joMessage.has("message")) {
            return joMessage.get("message").toString();
        }
    } catch (JSONException e) {
    }
    return "Unknown Error";
}

From source file:org.eldslott.armory.utils.JsonUtils.java

public static Integer getInt(JSONObject jsonObject, String name) {
    try {/*from ww  w  .  j a  va 2 s.co m*/
        return Integer.parseInt((String) jsonObject.get(name));
    } catch (JSONException e) {
        Log.e(JsonUtils.class.toString(),
                "could not get from jsonObject for name '" + name + "': " + e.getMessage());
    } catch (Exception e) {
        Log.e(JsonUtils.class.toString(), "could not parse int for name " + name + "': " + e.getMessage());

        try {
            Log.e(JsonUtils.class.toString(), "value of unparseable int was: " + jsonObject.get(name));
        } catch (Exception e2) {
            Log.e(JsonUtils.class.toString(),
                    "could not get unparseable int value from jsonObject: " + e2.getMessage());
        }
    }
    return null;
}

From source file:org.eldslott.armory.utils.JsonUtils.java

public static Double getDouble(JSONObject jsonObject, String name) {
    try {//  www.j a  v  a2  s.  co m
        return Double.parseDouble((String) jsonObject.get(name));
    } catch (JSONException e) {
        Log.e(JsonUtils.class.toString(),
                "could not get from jsonObject for name '" + name + "': " + e.getMessage());
    } catch (Exception e) {
        Log.e(JsonUtils.class.toString(), "could not parse double for name " + name + "': " + e.getMessage());

        try {
            Log.e(JsonUtils.class.toString(), "value of unparseable double was: " + jsonObject.get(name));
        } catch (Exception e2) {
            Log.e(JsonUtils.class.toString(),
                    "could not get unparseable double value from jsonObject: " + e2.getMessage());
        }
    }
    return null;
}