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:org.akop.ararat.io.WSJFormatter.java

@Override
public void read(Crossword.Builder builder, InputStream inputStream) throws IOException {
    InputStreamReader reader = new InputStreamReader(inputStream, mEncoding);

    StringBuilder sb = new StringBuilder();
    int nread;/* w w w  . j av a2 s.  c  om*/
    char[] buffer = new char[4000];
    while ((nread = reader.read(buffer, 0, buffer.length)) > -1) {
        sb.append(buffer, 0, nread);
    }

    JSONObject obj;
    try {
        obj = new JSONObject(sb.toString());
    } catch (JSONException e) {
        throw new FormatException("Error parsing JSON object", e);
    }

    JSONObject dataObj = obj.optJSONObject("data");
    if (dataObj == null) {
        throw new FormatException("Missing 'data'");
    }

    JSONObject copyObj = dataObj.optJSONObject("copy");
    if (copyObj == null) {
        throw new FormatException("Missing 'data.copy'");
    }

    JSONObject gridObj = copyObj.optJSONObject("gridsize");
    if (gridObj == null) {
        throw new FormatException("Missing 'data.copy.gridsize'");
    }

    builder.setTitle(copyObj.optString("title"));
    builder.setDescription(copyObj.optString("description"));
    builder.setCopyright(copyObj.optString("publisher"));
    builder.setAuthor(copyObj.optString("byline"));

    String pubString = copyObj.optString("date-publish");
    try {
        builder.setDate(PUBLISH_DATE_FORMAT.parse(pubString).getTime());
    } catch (ParseException e) {
        throw new FormatException("Can't parse '" + pubString + "' as publish date");
    }

    int width = gridObj.optInt("cols");
    int height = gridObj.optInt("rows");

    builder.setWidth(width);
    builder.setHeight(height);

    readClues(builder, copyObj, Grid.parseJSON(dataObj.optJSONArray("grid"), width, height));
}

From source file:org.akop.ararat.io.WSJFormatter.java

private static void readClues(Crossword.Builder builder, JSONObject copyObj, Grid grid) {
    JSONArray cluesArray = copyObj.optJSONArray("clues");
    if (cluesArray == null) {
        throw new FormatException("Missing 'data.copy.clues[]'");
    } else if (cluesArray.length() != 2) {
        throw new FormatException("Unexpected clues length of '" + cluesArray.length() + "'");
    }//from   w  w  w  .j ava  2s  .  com

    JSONArray wordsArray = copyObj.optJSONArray("words");
    if (wordsArray == null) {
        throw new FormatException("Missing 'data.copy.words[]'");
    }

    // We'll need this to assign x/y locations to each clue
    SparseArray<Word> words = new SparseArray<>();
    for (int i = 0, n = wordsArray.length(); i < n; i++) {
        Word word;
        try {
            word = Word.parseJSON(wordsArray.optJSONObject(i));
        } catch (Exception e) {
            throw new FormatException("Error parsing 'data.copy.words[" + i + "]'", e);
        }

        words.put(word.mId, word);
    }

    // Go through the list of clues
    for (int i = 0, n = cluesArray.length(); i < n; i++) {
        JSONObject clueObj = cluesArray.optJSONObject(i);
        if (clueObj == null) {
            throw new FormatException("'data.copy.clues[" + i + "]' is null");
        }

        JSONArray subcluesArray = clueObj.optJSONArray("clues");
        if (subcluesArray == null) {
            throw new FormatException("Missing 'data.copy.clues[" + i + "].clues'");
        }

        int dir;
        String clueDir = clueObj.optString("title");
        if ("Across".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_ACROSS;
        } else if ("Down".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_DOWN;
        } else {
            throw new FormatException("Invalid direction: '" + clueDir + "'");
        }

        for (int j = 0, o = subcluesArray.length(); j < o; j++) {
            JSONObject subclue = subcluesArray.optJSONObject(j);
            Word word = words.get(subclue.optInt("word", -1));
            if (word == null) {
                throw new FormatException(
                        "No matching word for clue at 'data.copy.clues[" + i + "].clues[" + j + "].word'");
            }

            Crossword.Word.Builder wb = new Crossword.Word.Builder().setDirection(dir)
                    .setHint(subclue.optString("clue")).setNumber(subclue.optInt("number"))
                    .setStartColumn(word.mCol).setStartRow(word.mRow);

            if (dir == Crossword.Word.DIR_ACROSS) {
                for (int k = word.mCol, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[word.mRow][k];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + word.mRow + "][" + k + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            } else {
                for (int k = word.mRow, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[k][word.mCol];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + k + "][" + word.mCol + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            }

            builder.addWord(wb.build());
        }
    }
}

From source file:com.appsimobile.appsii.module.weather.ImageDownloadHelper.java

public static void getEligiblePhotosFromResponse(@Nullable JSONObject jsonObject, List<PhotoInfo> result,
        int minDimension) {
    result.clear();//from   w w w  . j  a v  a 2  s. c o m

    if (jsonObject == null)
        return;

    JSONObject photos = jsonObject.optJSONObject("photos");
    if (photos == null)
        return;

    JSONArray photoArr = photos.optJSONArray("photo");
    if (photoArr == null)
        return;

    int N = photoArr.length();
    for (int i = 0; i < N; i++) {
        JSONObject object = photoArr.optJSONObject(i);
        if (object == null)
            continue;
        String id = object.optString("id");
        if (TextUtils.isEmpty(id))
            continue;
        String urlH = urlFromImageObject(object, "url_h", "width_h", "height_h", minDimension - 100);
        String urlO = urlFromImageObject(object, "url_o", "width_o", "height_o", minDimension - 100);

        if (urlH != null) {
            result.add(new PhotoInfo(id, urlH));
        } else if (urlO != null) {
            result.add(new PhotoInfo(id, urlO));
        }
    }

}

From source file:com.appsimobile.appsii.module.weather.ImageDownloadHelper.java

static String urlFromImageObject(JSONObject object, String u, String w, String h, int minDimension) {
    String url = object.optString(u);
    if (TextUtils.isEmpty(url))
        return null;
    int heightO = object.optInt(h);
    int widthO = object.optInt(w);
    if (heightO < minDimension || widthO < minDimension)
        return null;
    return url;/*ww  w  . j a  v  a2s  .co  m*/
}

From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java

private boolean load() {
    String jsonString = context.getSharedPreferences("contacts", Context.MODE_PRIVATE).getString("json", null);
    if (jsonString == null)
        return false;

    List<Participant> participants;
    try {/* w w w  . j  a  v a 2 s  .c o  m*/
        JSONArray contactsJson = new JSONArray(jsonString);
        participants = new ArrayList<Participant>(contactsJson.length());
        for (int i = 0; i < contactsJson.length(); i++) {
            JSONObject contactJson = contactsJson.getJSONObject(i);
            Participant participant = new Participant();
            participant.userId = contactJson.optString("id");
            participant.firstName = contactJson.optString("first_name");
            participant.lastName = contactJson.optString("last_name");
            participants.add(participant);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Error while saving", e);
        return false;
    }

    setParticipants(participants);

    return true;
}

From source file:org.catnut.metadata.User.java

@Override
public ContentValues convert(JSONObject json) {
    ContentValues user = new ContentValues();
    user.put(BaseColumns._ID, json.optLong(Constants.ID));
    user.put(screen_name, json.optString(screen_name));
    user.put(name, json.optString(name));
    user.put(province, json.optInt(province));
    user.put(city, json.optInt(city));/*from ww w.  j  a  v  a2  s . c  o  m*/
    user.put(location, json.optString(location));
    user.put(description, json.optString(description));
    user.put(url, json.optString(url));
    user.put(profile_image_url, json.optString(profile_image_url));
    user.put(cover_image, json.optString(cover_image));
    user.put(cover_image_phone, json.optString(cover_image_phone));
    user.put(profile_url, json.optString(profile_url));
    user.put(domain, json.optString(domain));
    user.put(weihao, json.optString(weihao));
    user.put(gender, json.optString(gender));
    user.put(followers_count, json.optInt(followers_count));
    user.put(friends_count, json.optInt(friends_count));
    user.put(statuses_count, json.optInt(statuses_count));
    user.put(favourites_count, json.optInt(favourites_count));
    user.put(created_at, json.optString(created_at));
    user.put(following, json.optBoolean(following));
    user.put(allow_all_act_msg, json.optBoolean(allow_all_act_msg));
    user.put(geo_enabled, json.optBoolean(geo_enabled));
    user.put(verified, json.optBoolean(verified));
    user.put(verified_type, json.optInt(verified_type));
    user.put(remark, json.optString(remark));
    //      user.put(ptype, json.optInt(ptype));
    user.put(allow_all_comment, json.optBoolean(allow_all_comment));
    user.put(avatar_large, json.optString(avatar_large));
    user.put(avatar_hd, json.optString(avatar_hd));
    user.put(verified_reason, json.optString(verified_reason));
    user.put(follow_me, json.optBoolean(follow_me));
    user.put(online_status, json.optInt(online_status));
    user.put(bi_followers_count, json.optInt(bi_followers_count));
    user.put(lang, json.optString(lang));
    //      user.put(star, json.optString(star));
    //      user.put(mbtype, json.optInt(mbtype));
    //      user.put(mbrank, json.optInt(mbrank));
    //      user.put(block_word, json.optInt(block_word));
    // ?id
    if (json.has(SINGLE)) {
        user.put(status_id, json.optJSONObject(Status.SINGLE).optLong(Constants.ID));
    }
    return user;
}

From source file:com.basetechnology.s0.agentserver.field.MoneyField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("money"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    double defaultValue = fieldJson.has("default_value") ? fieldJson.optDouble("default_value") : 0;
    double minValue = fieldJson.has("min_value") ? fieldJson.optDouble("min_value") : Double.MIN_VALUE;
    double maxValue = fieldJson.has("max_value") ? fieldJson.optDouble("max_value") : Double.MAX_VALUE;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new MoneyField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth,
            compute);//  w  w w.  j a  v a2  s.c om
}

From source file:com.nascent.android.glass.glasshackto.greenpfinder.model.GreenPSpots.java

/**
 * Converts a JSON object that represents a place into a {@link Place} object.
 *///  ww w  . ja  v a 2 s.  com
private ParkingLot jsonObjectToParkingLot(JSONObject object) {
    int id = object.optInt("id");
    String name = object.optString("address");
    String rate = object.optString("rate");
    double latitude = object.optDouble("lat", Double.NaN);
    double longitude = object.optDouble("lng", Double.NaN);

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

From source file:com.mindmeapp.extensions.ExtensionData.java

/**
 * Deserializes the given JSON representation of extension data, populating this
 * object.//from w w  w.java2 s.  co  m
 */
public void deserialize(JSONObject data) throws JSONException {
    this.mVisible = data.optBoolean(KEY_VISIBLE);
    this.mIcon = data.optInt(KEY_ICON);
    String iconUriString = data.optString(KEY_ICON_URI);
    this.mIconUri = TextUtils.isEmpty(iconUriString) ? null : Uri.parse(iconUriString);
    this.mStatusToDisplay = data.optString(KEY_STATUS_TO_DISPLAY);
    this.mStatusToSpeak = data.optString(KEY_STATUS_TO_SPEAK);
    this.mContentDescription = data.optString(KEY_CONTENT_DESCRIPTION);
    this.mBackground = data.optInt(KEY_BACKGROUND);
    String backgroundUriString = data.optString(KEY_BACKGROUND_URI);
    this.mBackgroundUri = TextUtils.isEmpty(backgroundUriString) ? null : Uri.parse(backgroundUriString);

    //Build back the Locale object
    String language = data.optString(KEY_LOCALE_LANGUAGE);
    String country = data.optString(KEY_LOCALE_COUNTRY);
    if (TextUtils.isEmpty(country)) {
        this.mLanguageToSpeak = new Locale(language);
    } else {
        this.mLanguageToSpeak = new Locale(language, country);
    }

}

From source file:com.cantwellcode.fitfriend.purchases.Purchase.java

public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;/*from  w  w w. j  a v  a  2  s  .  co m*/
    mOriginalJson = jsonPurchaseInfo;
    JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mSignature = signature;
}