Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:com.vk.sdkweb.api.model.VKApiDocument.java

/**
 * Fills a Doc instance from JSONObject.
 *//* w  w  w. ja va 2  s  . c  o  m*/
public VKApiDocument parse(JSONObject jo) {
    id = jo.optInt("id");
    owner_id = jo.optInt("owner_id");
    title = jo.optString("title");
    size = jo.optLong("size");
    ext = jo.optString("ext");
    url = jo.optString("url");
    access_key = jo.optString("access_key");

    photo_100 = jo.optString("photo_100");
    if (!TextUtils.isEmpty(photo_100)) {
        photo.add(VKApiPhotoSize.create(photo_100, 100, 75));
    }
    photo_130 = jo.optString("photo_130");
    if (!TextUtils.isEmpty(photo_130)) {
        photo.add(VKApiPhotoSize.create(photo_130, 130, 100));
    }
    photo.sort();
    return this;
}

From source file:org.cloudsky.cordovaPlugins.BarcodeminCDV.java

/**
 * Executes the request./*  w w w  .  j  av  a 2  s .c  o m*/
 *
 * This method is called from the WebView thread. To do a non-trivial amount of work, use:
 *     cordova.getThreadPool().execute(runnable);
 *
 * To run on the UI thread, use:
 *     cordova.getActivity().runOnUiThread(runnable);
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return                Whether the action was valid.
 *
 * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
 */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    this.callbackContext = callbackContext;
    this.requestArgs = args;

    if (action.equals(ENCODE)) {
        JSONObject obj = args.optJSONObject(0);
        if (obj != null) {
            String type = obj.optString(TYPE);
            String data = obj.optString(DATA);

            // If the type is null then force the type to text
            if (type == null) {
                type = TEXT_TYPE;
            }

            if (data == null) {
                callbackContext.error("User did not specify data to encode");
                return true;
            }

            encode(type, data);
        } else {
            callbackContext.error("User did not specify data to encode");
            return true;
        }
    } else if (action.equals("scanBarcode")) {

        //android permission auto add
        if (!hasPermisssion()) {
            requestPermissions(0);
        } else {
            scan(args);
        }
    } else {
        return false;
    }
    return true;
}

From source file:org.cloudsky.cordovaPlugins.BarcodeminCDV.java

/**
 * Starts an intent to scan and decode a barcode.
 *///from   www.  java2 s .  com
public void scan(final JSONArray args) {

    final CordovaPlugin that = this;

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            Intent intentScan = new Intent(SCAN_INTENT);
            intentScan.addCategory(Intent.CATEGORY_DEFAULT);

            // add config as intent extras
            if (args.length() > 0) {

                JSONObject obj;
                JSONArray names;
                String key;
                Object value;

                for (int i = 0; i < args.length(); i++) {

                    try {
                        obj = args.getJSONObject(i);
                    } catch (JSONException e) {
                        Log.i("CordovaLog", e.getLocalizedMessage());
                        continue;
                    }

                    names = obj.names();
                    for (int j = 0; j < names.length(); j++) {
                        try {
                            key = names.getString(j);
                            value = obj.get(key);

                            if (value instanceof Integer) {
                                intentScan.putExtra(key, (Integer) value);
                            } else if (value instanceof String) {
                                intentScan.putExtra(key, (String) value);
                            }

                        } catch (JSONException e) {
                            Log.i("CordovaLog", e.getLocalizedMessage());
                        }
                    }

                    intentScan.putExtra(Intents.Scan.CAMERA_ID,
                            obj.optBoolean(PREFER_FRONTCAMERA, false) ? 1 : 0);
                    intentScan.putExtra(Intents.Scan.SHOW_FLIP_CAMERA_BUTTON,
                            obj.optBoolean(SHOW_FLIP_CAMERA_BUTTON, false));
                    if (obj.has(FORMATS)) {
                        intentScan.putExtra(Intents.Scan.FORMATS, obj.optString(FORMATS));
                    }
                    if (obj.has(PROMPT)) {
                        intentScan.putExtra(Intents.Scan.PROMPT_MESSAGE, obj.optString(PROMPT));
                    }
                    //if (obj.has(ORIENTATION)) {
                    //intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, obj.optString(ORIENTATION));
                    intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, "false");
                    //}
                }

            }

            // avoid calling other phonegap apps
            intentScan.setPackage(that.cordova.getActivity().getApplicationContext().getPackageName());

            that.cordova.startActivityForResult(that, intentScan, REQUEST_CODE);
        }
    });
}

From source file:com.melniqw.instagramsdk.Video.java

public static Video fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Video video = new Video();
    JSONObject lowResolutionJSON = o.optJSONObject("low_resolution");
    video.lowResolution.url = lowResolutionJSON.optString("url");
    video.lowResolution.width = lowResolutionJSON.optInt("width");
    video.lowResolution.height = lowResolutionJSON.optInt("height");
    JSONObject standartResolutionJSON = o.optJSONObject("standard_resolution");
    video.standartResolution.url = standartResolutionJSON.optString("url");
    video.standartResolution.width = standartResolutionJSON.optInt("width");
    video.standartResolution.height = standartResolutionJSON.optInt("height");
    JSONObject lowBandwidthJSON = o.optJSONObject("low_bandwidth");
    video.lowBandwidth.url = lowBandwidthJSON.optString("url");
    video.lowBandwidth.width = lowBandwidthJSON.optInt("width");
    video.lowBandwidth.height = lowBandwidthJSON.optInt("height");
    return video;
}

From source file:info.zamojski.soft.towercollector.parsers.update.UpdateFeedParser.java

private String getVersionName(JSONObject object) throws JSONException {
    return object.optString(VERSION_NAME);
}

From source file:mobi.carton.glass.model.Landmarks.java

/**
 * Converts a JSON object that represents a place into a {@link Place} object.
 *//* ww w .  j a  v a2 s.com*/
private Place jsonObjectToPlace(JSONObject object) {
    String name = object.optString("name");
    double latitude = object.optDouble("latitude", Double.NaN);
    double longitude = object.optDouble("longitude", Double.NaN);

    if (!name.isEmpty() && !Double.isNaN(latitude) && !Double.isNaN(longitude)) {
        return new Place(latitude, longitude, name);
    } else {
        return null;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.JoinNotificationObj.java

@Override
public Pair<JSONObject, byte[]> handleUnprocessed(final Context context, JSONObject obj) {
    if (DBG)/*from   www  .j  a v a 2 s.  co m*/
        Log.i(TAG, "Message to update group. ");
    String feedName = obj.optString("feedName");
    final Uri uri = Uri.parse(obj.optString(JoinNotificationObj.URI));
    final GroupProviders.GroupProvider h = GroupProviders.forUri(uri);
    final DBHelper helper = DBHelper.getGlobal(context);
    final IdentityProvider ident = new DBIdentityProvider(helper);
    Maybe<Group> mg = helper.groupByFeedName(feedName);
    try {
        // group exists already, load view
        final Group g = mg.get();

        GroupProviders.runBackgroundGroupTask(g.id, new Runnable() {
            public void run() {
                Collection<Contact> existingContacts = g.contactCollection(helper);

                h.handle(g.id, uri, context, g.version, false);

                Collection<Contact> newContacts = g.contactCollection(helper);
                newContacts.removeAll(existingContacts);
                Helpers.resendProfile(context, newContacts, true);
            }
        });
    } catch (Maybe.NoValError e) {
    }
    ident.close();

    helper.close();
    return null;
}

From source file:se.chalmers.watchme.utils.MovieHelper.java

/**
 * Get the URL for a poster from a JSONArray of poster objects.
 * //from  w  w  w. j  ava  2s .c  o m
 * <p>Since Java lacks sane collection methods like select, map, etc al,
 * we have to do this by ourselves.</p>
 * 
 * <p>From a JSONArray of posters, get the *first* URL that matches the 
 * <code>size</code> parameter.</p>
 * 
 * @param posters A non-null JSONArray of posters. Assumes the JSONArray is
 * organized as <code>image</code> objects with the keys <code>size</code>
 * and <code>url</code>.
 * @param size The desired size
 * @return A URL as string with the first matching poster size. Otherwise null.
 */
public static String getPosterFromCollection(JSONArray posters, Movie.PosterSize size) {
    String url = null;

    if (posters != null && posters.length() > 0) {
        for (int i = 0; i < posters.length(); i++) {
            JSONObject image = posters.optJSONObject(i).optJSONObject("image");

            if (image.optString("size").equals(size.getSize())) {
                url = image.optString("url");
                break;
            }
        }
    }

    return url;
}

From source file:se.chalmers.watchme.utils.MovieHelper.java

/**
 * Convert a JSONArray of Movies to a list of Movies
 * /*  www  .ja  v a  2s  .  c o  m*/
 * <p>Each Movie object is initialized with the attribute
 * <code>original_name</code> from the input array. The 
 * attribute <code>imdb_id</code> is also set on the movie.</p>
 * 
 * @param input The JSONArray of movies as JSONObjects
 * @return A List of Movies
 */
public static List<Movie> jsonArrayToMovieList(JSONArray input) {
    List<Movie> list = new ArrayList<Movie>();

    // Parse the JSON objects and add to list
    for (int i = 0; i < input.length(); i++) {
        JSONObject o = input.optJSONObject(i);

        Movie movie = new Movie(o.optString(Movie.JSON_KEY_NAME));
        // Don't forget the ID
        movie.setApiID(o.optInt(Movie.JSON_KEY_ID));
        list.add(movie);
    }

    return list;
}

From source file:com.ammobyte.radioreddit.api.PerformLogin.java

@Override
protected Boolean doInBackground(String... params) {
    final String username = params[0];
    final String password = params[1];

    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        return false;
    }//w w w . j av a  2s.  c om

    // Prepare POST, execute it, parse response as JSON
    JSONObject response = null;
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost("https://ssl.reddit.com/api/login");
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("user", username));
        nameValuePairs.add(new BasicNameValuePair("passwd", password));
        nameValuePairs.add(new BasicNameValuePair("api_type", "json"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpPost.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpPost);
        final String responseBody = EntityUtils.toString(httpResponse.getEntity());
        if (MusicService.DEBUG) {
            Log.i(RedditApi.TAG, "Reddit API login response: " + responseBody);
        }
        response = new JSONObject(responseBody);
        response = response.getJSONObject("json");
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while performing login", e);
        return false;
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while performing login", e);
        return false;
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while performing login", e);
        return false;
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while performing login", e);
        return false;
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while performing login", e);
        return false;
    }

    // Check for failure 
    if (response == null) {
        Log.i(RedditApi.TAG, "Response was null while performing login");
        return false;
    }

    // Check for errors
    final JSONArray errors = response.optJSONArray("errors");
    if (errors == null || errors.length() > 0) {
        Log.i(RedditApi.TAG, "Response has errors while performing login");
        return false;
    }

    // Check for data
    final JSONObject data = response.optJSONObject("data");
    if (data == null) {
        Log.i(RedditApi.TAG, "Response missing data while performing login");
        return false;
    }

    // Get modhash and cookie from data
    mUser = username;
    mModhash = data.optString("modhash");
    mCookie = data.optString("cookie");
    if (mModhash.length() == 0 || mCookie.length() == 0) {
        Log.i(RedditApi.TAG, "Response missing modhash/cookie while performing login");
        return false;
    }

    return true;
}