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.mariotaku.twidere.extension.mediauploader.util.ParseUtils.java

public static Bundle jsonToBundle(final String string) {
    final Bundle bundle = new Bundle();
    if (string != null) {
        try {/*from   w  w w . jav a2s. c om*/
            final JSONObject json = new JSONObject(string);
            final Iterator<?> it = json.keys();
            while (it.hasNext()) {
                final Object key_obj = it.next();
                if (key_obj == null) {
                    continue;
                }
                final String key = key_obj.toString();
                final Object value = json.get(key);
                if (value instanceof Boolean) {
                    bundle.putBoolean(key, json.optBoolean(key));
                } else if (value instanceof Integer) {
                    // Simple workaround for account_id
                    if (shouldPutLong(key)) {
                        bundle.putLong(key, json.optLong(key));
                    } else {
                        bundle.putInt(key, json.optInt(key));
                    }
                } else if (value instanceof Long) {
                    bundle.putLong(key, json.optLong(key));
                } else if (value instanceof String) {
                    bundle.putString(key, json.optString(key));
                } else {
                    Log.w(LOGTAG,
                            "Unknown type " + value.getClass().getSimpleName() + " in arguments key " + key);
                }
            }
        } catch (final JSONException e) {
            e.printStackTrace();
        } catch (final ClassCastException e) {
            e.printStackTrace();
        }
    }
    return bundle;
}

From source file:com.rukman.emde.smsgroups.platform.GMSContactOperations.java

public static long addGroupToContacts(Context context, ContentProviderClient provider, Account account,
        JSONObject group, SyncResult result)
        throws RemoteException, OperationApplicationException, JSONException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation.Builder op = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
            .withValue(RawContacts.ACCOUNT_TYPE, GMSApplication.ACCOUNT_TYPE)
            .withValue(RawContacts.ACCOUNT_NAME, account.name)
            .withValue(RawContacts.SOURCE_ID, group.getString(JSONKeys.KEY_ID));
    ops.add(op.build());/*from w ww .  ja v  a  2 s.co  m*/
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, group.getString(JSONKeys.KEY_NAME));
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.Phone.NUMBER, group.get(JSONKeys.KEY_PHONE))
            .withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MAIN);
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE).withYieldAllowed(true);
    ops.add(op.build());
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        is = context.getAssets().open("gms.png", AssetManager.ACCESS_BUFFER);
        baos = new ByteArrayOutputStream();
        int value = is.read();
        while (value != -1) {
            baos.write(value);
            value = is.read();
        }
        op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray())
                .withYieldAllowed(true);
        ops.add(op.build());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (IOException ignore) {
        }
    }
    ContentProviderResult[] results = provider.applyBatch(ops);
    return (results[0].uri != null) ? ContentUris.parseId(results[0].uri) : -1L;
}

From source file:com.athena.network.CubeiaClient.java

public void sendCreateTableRequest(int stake, int agMin, int maxPlayer, int vipMin, JSONObject jobj) {
    unRegistryLobby();//  www.ja  v  a 2 s .co  m
    CreateTableRequestPacket packet = new CreateTableRequestPacket();
    packet.gameid = User.gameId;
    packet.seats = (byte) maxPlayer;
    packet.seq = 1;
    packet.invitees = new int[0];
    packet.params = new ArrayList<Param>();
    try {
        if (jobj == null) {
            jobj = new JSONObject();
        }
        jobj.put("gameId", User.gameId);
        jobj.put("Name", "nhao` zo^ !");
        jobj.put("Mark", stake);
        jobj.put("gaAGmeId", agMin);
        jobj.put("Vip", vipMin);
        jobj.put("Player", maxPlayer);

        @SuppressWarnings("unchecked")
        Iterator<String> i = jobj.keys();
        while (i.hasNext()) {
            String nparam = i.next();
            Object oparam = jobj.get(nparam);
            Param param = ParameterUtil.createParam(nparam, oparam);
            packet.params.add(param);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    send(packet);
}

From source file:org.loklak.api.iot.FossasiaPushServlet.java

@Override
protected void customProcessing(JSONObject message) {

    JSONObject location = (JSONObject) message.get("location");

    final Double longitude = (Double) location.get("lon");
    final Double latitude = (Double) location.get("lat");

    JSONArray location_point = new JSONArray();
    location_point.put(longitude);//w  ww.ja v  a 2  s. c  om
    location_point.put(latitude);
    message.put("location_point", location_point);
    message.put("location_mark", location_point);
}

From source file:produvia.com.scanner.DeviceCard.java

private static String extractStringFromJson(String field, JSONObject json) throws JSONException {
    if (json.has(field) && json.get(field) != null && !json.getString(field).equals("null")) {
        return json.getString(field);
    }//from  www .j  a va 2s . co  m
    return "";
}

From source file:com.github.koraktor.steamcondenser.community.GameItem.java

/**
 * Creates a new instance of a GameItem with the given data
 *
 * @param inventory The inventory this item is contained in
 * @param itemData The data specifying this item
 * @throws WebApiException on Web API errors
 *//*from   w  ww.  j  av  a2 s .  c  o m*/
public GameItem(GameInventory inventory, JSONObject itemData) throws SteamCondenserException {
    this.inventory = inventory;

    try {
        this.defindex = itemData.getInt("defindex");
        this.backpackPosition = (int) itemData.getLong("inventory") & 0xffff;
        this.count = itemData.getInt("quantity");
        this.craftable = !itemData.optBoolean("flag_cannot_craft");
        this.id = itemData.getInt("id");
        this.itemClass = this.getSchemaData().getString("item_class");
        this.itemSet = this.inventory.getItemSchema().getItemSets()
                .get(this.getSchemaData().optString("item_set"));
        this.level = itemData.getInt("level");
        this.name = this.getSchemaData().getString("item_name");
        this.preliminary = (itemData.getLong("inventory") & 0x40000000) != 0;
        this.originalId = itemData.getInt("original_id");
        this.quality = this.inventory.getItemSchema().getQualities().get(itemData.getInt("quality"));
        this.tradeable = !itemData.optBoolean("flag_cannot_trade");
        this.type = this.getSchemaData().getString("item_type_name");

        if (itemData.has("origin")) {
            this.origin = this.inventory.getItemSchema().getOrigins().get(itemData.getInt("origin"));
        }

        JSONArray attributesData = this.getSchemaData().optJSONArray("attributes");
        if (attributesData == null) {
            attributesData = new JSONArray();
        }
        if (itemData.has("attributes")) {
            JSONArray itemAttributes = itemData.getJSONArray("attributes");
            for (int i = 0; i < itemAttributes.length(); i++) {
                attributesData.put(itemAttributes.get(i));
            }
        }

        this.attributes = new ArrayList<JSONObject>();
        for (int i = 0; i < attributesData.length(); i++) {
            JSONObject attributeData = attributesData.getJSONObject(i);
            Object attributeKey = attributeData.opt("defindex");
            if (attributeKey == null) {
                attributeKey = attributeData.opt("name");
            }

            if (attributeKey != null) {
                JSONObject schemaAttributeData = inventory.getItemSchema().getAttributes().get(attributeKey);
                for (String key : JSONObject.getNames(schemaAttributeData)) {
                    attributeData.put(key, schemaAttributeData.get(key));
                }
                this.attributes.add(attributeData);
            }
        }
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}

From source file:cn.ttyhuo.view.UserView.java

private int setupTruckInfo(Context context, JSONObject jObject, JSONObject jsonObject, int verifyFlag)
        throws JSONException {
    if (JSONUtil.getBoolFromJson(jObject, "driverVerify")) {
        verifyFlag += 2;/*from w ww.  j  a v a2s. com*/
    }

    if (jObject.get("truckInfo") == JSONObject.NULL) {
        ly_truck.setVisibility(View.GONE);
        if (line_truck != null)
            line_truck.setVisibility(View.GONE);

        if (line_route != null)
            line_route.setVisibility(View.GONE);
        if (ly_route != null)
            ly_route.setVisibility(View.GONE);

        if (ll_driverAge != null)
            ll_driverAge.setVisibility(View.GONE);

        tv_licensePlate.setVisibility(View.GONE);

        if (tv_driverShuoShuo != null)
            tv_driverShuoShuo.setVisibility(View.GONE);
    } else {
        ly_truck.setVisibility(View.VISIBLE);
        if (line_truck != null)
            line_truck.setVisibility(View.VISIBLE);

        if (ly_route != null)
            ly_route.setVisibility(View.GONE);
        if (line_route != null)
            line_route.setVisibility(View.GONE);
        //            try{
        //                if(jsonObject.has("userRoutes") && jsonObject.getJSONArray("userRoutes").length() > 0)
        //                    ly_route.setVisibility(View.VISIBLE);
        //                else
        //                    ly_route.setVisibility(View.GONE);
        //            }
        //            catch (Exception e){}
        if (ll_driverAge != null)
            ll_driverAge.setVisibility(View.VISIBLE);
        tv_licensePlate.setVisibility(View.VISIBLE);

        try {
            JSONObject truckInfoJsonObj = jObject.getJSONObject("truckInfo");

            Integer truckType = JSONUtil.getIntFromJson(truckInfoJsonObj, "truckType", 0);
            if (truckType != null && truckType > 0)
                tv_truckType.setText(ConstHolder.TruckTypeItems[truckType - 1]);
            else
                tv_truckType.setText("");

            JSONUtil.setValueFromJson(tv_licensePlate, truckInfoJsonObj, "licensePlate", "", true);

            //NOTE:  tv_truckWidth 
            if (tv_truckWidth == null) {
                tv_loadLimit.setText(context.getResources().getString(R.string.user_loadLimitStr,
                        JSONUtil.getStringFromJson(truckInfoJsonObj, "loadLimit", "")));
                tv_truckLength.setText(context.getResources().getString(R.string.user_truckLengthStr,
                        JSONUtil.getStringFromJson(truckInfoJsonObj, "truckLength", "")));
            } else {
                JSONUtil.setValueFromJson(tv_loadLimit, truckInfoJsonObj, "loadLimit", 0.0, "", true);
                JSONUtil.setValueFromJson(tv_truckLength, truckInfoJsonObj, "truckLength", 0.0, "", true);
            }

            JSONUtil.setValueFromJson(tv_truckWidth, truckInfoJsonObj, "truckWidth", 0, "", true);
            JSONUtil.setValueFromJson(tv_truckHeight, truckInfoJsonObj, "truckHeight", 0, "", true);
            JSONUtil.setValueFromJson(tv_modelNumber, truckInfoJsonObj, "modelNumber", "");
            JSONUtil.setValueFromJson(tv_seatingCapacity, truckInfoJsonObj, "seatingCapacity", 0, "",
                    true);

            if (tv_driverShuoShuo != null) {
                String tmpValue = JSONUtil.getStringFromJson(truckInfoJsonObj, "memo", "");
                if (tmpValue.isEmpty())
                    tv_driverShuoShuo.setVisibility(View.GONE);
                else {
                    tv_driverShuoShuo.setVisibility(View.VISIBLE);
                    //NOTE:  tv_truckWidth 
                    if (tv_truckWidth == null && tmpValue.length() > 38)
                        tmpValue = tmpValue.substring(0, 35) + "...";
                    tv_driverShuoShuo.setText(tmpValue);
                }
            }

            int driverAge = JSONUtil.getIntFromJson(truckInfoJsonObj, "releaseYear", 0);
            if (driverAge > 0) {
                Integer age = new Date().getYear() + 1900 - driverAge;
                tv_driverAge.setText(context.getResources().getString(R.string.user_driverAgeStr, age));
            } else {
                tv_driverAge.setText("");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return verifyFlag;
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * 1. Resets profile to get fresh slate//ww  w.  j av  a 2 s.  co m
 * 2. Updates active server group to one from json
 * 3. For each path in json, sets request/response enabled
 * 4. Adds active overrides to each path
 * 5. Update arguments and repeat count for each override
 *
 * @param profileBackup JSON containing server configuration and overrides to activate
 * @param profileId Profile to update
 * @param clientUUID Client UUID to apply update to
 * @return
 * @throws Exception Array of errors for things that could not be imported
 */
public void setProfileFromBackup(JSONObject profileBackup, int profileId, String clientUUID) throws Exception {
    // Reset the profile before applying changes
    ClientService clientService = ClientService.getInstance();
    clientService.reset(profileId, clientUUID);
    clientService.updateActive(profileId, clientUUID, true);
    JSONArray errors = new JSONArray();

    // Change to correct server group
    JSONObject activeServerGroup = profileBackup.getJSONObject(Constants.BACKUP_ACTIVE_SERVER_GROUP);
    int activeServerId = getServerIdFromName(activeServerGroup.getString(Constants.NAME), profileId);
    if (activeServerId == -1) {
        errors.put(formErrorJson("Server Error", "Cannot change to '"
                + activeServerGroup.getString(Constants.NAME) + "' - Check Server Group Exists"));
    } else {
        Client clientToUpdate = ClientService.getInstance().findClient(clientUUID, profileId);
        ServerRedirectService.getInstance().activateServerGroup(activeServerId, clientToUpdate.getId());
    }

    JSONArray enabledPaths = profileBackup.getJSONArray(Constants.ENABLED_PATHS);
    PathOverrideService pathOverrideService = PathOverrideService.getInstance();
    OverrideService overrideService = OverrideService.getInstance();

    for (int i = 0; i < enabledPaths.length(); i++) {
        JSONObject path = enabledPaths.getJSONObject(i);
        int pathId = pathOverrideService.getPathId(path.getString(Constants.PATH_NAME), profileId);
        // Set path to have request/response enabled as necessary
        try {
            if (path.getBoolean(Constants.REQUEST_ENABLED)) {
                pathOverrideService.setRequestEnabled(pathId, true, clientUUID);
            }

            if (path.getBoolean(Constants.RESPONSE_ENABLED)) {
                pathOverrideService.setResponseEnabled(pathId, true, clientUUID);
            }
        } catch (Exception e) {
            errors.put(formErrorJson("Path Error",
                    "Cannot update path: '" + path.getString(Constants.PATH_NAME) + "' - Check Path Exists"));
            continue;
        }

        JSONArray enabledOverrides = path.getJSONArray(Constants.ENABLED_ENDPOINTS);

        /**
         * 2 for loops to ensure overrides are added with correct priority
         * 1st loop is priority currently adding override to
         * 2nd loop is to find the override with matching priority in profile json
         */
        for (int j = 0; j < enabledOverrides.length(); j++) {
            for (int k = 0; k < enabledOverrides.length(); k++) {
                JSONObject override = enabledOverrides.getJSONObject(k);
                if (override.getInt(Constants.PRIORITY) != j) {
                    continue;
                }

                int overrideId;
                // Name of method that can be used by error message as necessary later
                String overrideNameForError = "";
                // Get the Id of the override
                try {
                    // If method information is null, then the override is a default override
                    if (override.get(Constants.METHOD_INFORMATION) != JSONObject.NULL) {
                        JSONObject methodInformation = override.getJSONObject(Constants.METHOD_INFORMATION);
                        overrideNameForError = methodInformation.getString(Constants.METHOD_NAME);
                        overrideId = overrideService.getOverrideIdForMethod(
                                methodInformation.getString(Constants.CLASS_NAME),
                                methodInformation.getString(Constants.METHOD_NAME));
                    } else {
                        overrideNameForError = "Default Override";
                        overrideId = override.getInt(Constants.OVERRIDE_ID);
                    }

                    // Enable override and set repeat number and arguments
                    overrideService.enableOverride(overrideId, pathId, clientUUID);
                    overrideService.updateRepeatNumber(overrideId, pathId, override.getInt(Constants.PRIORITY),
                            override.getInt(Constants.REPEAT_NUMBER), clientUUID);
                    overrideService.updateArguments(overrideId, pathId, override.getInt(Constants.PRIORITY),
                            override.getString(Constants.ARGUMENTS), clientUUID);
                } catch (Exception e) {
                    errors.put(formErrorJson("Override Error", "Cannot add/update override: '"
                            + overrideNameForError + "' - Check Override Exists"));
                    continue;
                }
            }
        }
    }

    // Throw exception if any errors occured
    if (errors.length() > 0) {
        throw new Exception(errors.toString());
    }
}

From source file:com.karura.framework.plugins.UI.java

@JavascriptInterface
// #endif//from  w w  w . j  a  v a  2s.  co m
@SupportJavascriptInterface
@Description("Load the url into the webview.")
@Asynchronous(retVal = "none, will load the specified URL in the webview")
@Params({ @Param(name = "callId", description = "The method correlator between javascript and java."),
        @Param(name = "url", description = "URL to be loaded in the web browser"),
        @Param(name = "props", description = "Specifies the parameters for customizing the loadUrl experience. Look at "
                + "WAIT_KEY, OPEN_EXTR_KEY and CLEAR_HISTORY_KEY. If the OPEN_EXTR_KEY is specified then this object can also contain additional "
                + "parameters which need to be passed to the external viewer in the intent. The other keys can only be integer, boolean or string") })
public void loadUrl(final String callId, String url, JSONObject props) throws JSONException {
    Log.d(TAG, "loadUrl(" + url + "," + props + ")");
    int wait = 0;
    boolean openExternal = false;
    boolean clearHistory = false;

    // If there are properties, then set them on the Activity
    HashMap<String, Object> params = new HashMap<String, Object>();
    if (props != null) {
        JSONArray keys = props.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            if (key.equals(WAIT_KEY)) {
                wait = props.getInt(key);
            } else if (key.equalsIgnoreCase(OPEN_EXTR_KEY)) {
                openExternal = props.getBoolean(key);
            } else if (key.equalsIgnoreCase(CLEAR_HISTORY_KEY)) {
                clearHistory = props.getBoolean(key);
            } else {
                Object value = props.get(key);
                if (value == null) {

                } else if (value.getClass().equals(String.class)) {
                    params.put(key, (String) value);
                } else if (value.getClass().equals(Boolean.class)) {
                    params.put(key, (Boolean) value);
                } else if (value.getClass().equals(Integer.class)) {
                    params.put(key, (Integer) value);
                }
            }
        }
    }

    // If wait property, then delay loading

    if (wait > 0) {
        try {
            synchronized (this) {
                this.wait(wait);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    getWebView().showWebPage(url, openExternal, clearHistory, params);
}

From source file:org.collectionspace.chain.csp.persistence.services.relation.TestRelations.java

@Test
public void testRelationsThroughAPI() throws Exception {
    Storage ss = makeServicesStorage();//from ww  w.j  a  va  2s .c om
    //create 3 objects
    String obj1 = makeRecord(ss, "A");
    String obj2 = makeRecord(ss, "B");
    String obj3 = makeRecord(ss, "C");

    // relate obj1 and obj2
    String path = relate(ss, obj1, obj2);
    //relate  obj2 and obj3
    String path2 = relate(ss, obj2, obj3);

    // test relationship
    JSONObject data2 = ss.retrieveJSON("relations/main/" + path, new JSONObject());
    assertTrue(JSONUtils.checkJSONEquiv("CollectionObject/" + obj1, data2.getString("src")));
    assertTrue(JSONUtils.checkJSONEquiv("CollectionObject/" + obj2, data2.getString("dst")));
    assertTrue(JSONUtils.checkJSONEquiv("affects", data2.getString("type")));

    // update
    updaterelate(ss, path, obj1, obj3);

    // get
    JSONObject data3 = ss.retrieveJSON("relations/main/" + path, new JSONObject());
    assertTrue(JSONUtils.checkJSONEquiv("CollectionObject/" + obj1, data3.getString("src")));
    assertTrue(JSONUtils.checkJSONEquiv("CollectionObject/" + obj3, data3.getString("dst")));
    assertTrue(JSONUtils.checkJSONEquiv("affects", data3.getString("type")));

    //get list

    JSONObject searchRestriction = new JSONObject();
    searchRestriction.put("src", "collection-object/" + obj2);
    searchRestriction.put("type", "affects");

    // simple list
    //XXX CSPACE-1080 - will need to update if this is improved
    JSONObject datalist = ss.getPathsJSON("relations/main", searchRestriction);
    int truecount = 0;
    String[] paths = (String[]) datalist.get("listItems");
    log.info(datalist.toString());
    JSONObject pagination = datalist.getJSONObject("pagination");
    boolean pagbool = false;
    for (int i = 0; i < paths.length; i++) {
        if (paths[i].equals(path) || paths[i].equals(path2)) {
            truecount++;
        }
    }

    assertTrue(truecount > 0);

    // delete
    ss.deleteJSON("/relations/main/" + path);
    ss.deleteJSON("/relations/main/" + path2);

    // delete objects
    ss.deleteJSON("collection-object/" + obj1);
    ss.deleteJSON("collection-object/" + obj2);
    ss.deleteJSON("collection-object/" + obj3);

}