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.ESLM.Parser.ExerciseFactory.java

public static Instruction createInstruction(JSONObject JSONExercise) throws BadFormedJSONExerciseException {
    switch (JSONExercise.optString("type")) {
    case ("OneAnswerQuestion"): {
        String question = JSONExercise.getString("question");
        String[] answers = createAnswers(JSONExercise.getJSONArray("answers"));
        int correctAnswerIndex = JSONExercise.getInt("correctAnswer");
        return new OneAnswerInstruction(question, answers, correctAnswerIndex);
    }// ww w.  ja va  2  s  . c  o m
    case ("YesNoQuestion"): {
        String question = JSONExercise.getString("question");
        boolean correctAnswer = JSONExercise.getBoolean("correctAnswer");
        return new YesNoInstruction(question, correctAnswer);
    }
    case ("SimpleQuestion"): {
        String question = JSONExercise.getString("question");
        String answer = JSONExercise.getString("answer");
        return new SimpleQuestionInstruction(question, answer);
    }
    case ("IrregularVerbExercise"): {
        String infinitive = JSONExercise.getString("infinitive");
        String pastSimple = JSONExercise.getString("pastSimple");
        String pastParticiple = JSONExercise.getString("pastParticiple");
        String[] correctAnswer = { infinitive, pastSimple, pastParticiple };
        String translation = JSONExercise.getString("translation");
        boolean alsoRegular = JSONExercise.getBoolean("alsoRegular");
        return new IrregularVerbInstruction(correctAnswer, translation, alsoRegular);
    }
    case ("VocabularyExercise"): {
        String sourceLanguage = JSONExercise.getString("sourceLanguage");
        String goalLanguage = JSONExercise.getString("goalLanguage");
        JSONArray JSONVocabularyList = JSONExercise.getJSONArray("list");
        HashMap<String, String> vocabularyList = parseVocabularyList(JSONVocabularyList);
        return new VocabularyInstruction(vocabularyList, sourceLanguage, goalLanguage);
    }
    default:
        throw new BadFormedJSONExerciseException("No type or unknown type of exercise.", JSONExercise);
    }
}

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

/**
 * Fills a Country instance from JSONObject.
 *//*from   w w  w.  j  ava 2  s.c  om*/
public VKApiCountry parse(JSONObject from) {
    id = from.optInt("id");
    title = from.optString("title");
    return this;
}

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

@Override
public ContentValues convert(JSONObject json) {
    ContentValues tweet = new ContentValues();
    tweet.put(BaseColumns._ID, json.optLong(Constants.ID));
    tweet.put(created_at, json.optString(created_at));
    // ?jsonsql???
    tweet.put(columnText, json.optString(text));
    tweet.put(source, json.optString(source));
    tweet.put(favorited, json.optBoolean(favorited));
    tweet.put(truncated, json.optBoolean(truncated));
    // ??????//from   www. j av a2 s  .com
    JSONArray thumbs = json.optJSONArray(pic_urls);
    if (thumbs != null) {
        // json
        tweet.put(pic_urls, thumbs.toString());
    }
    tweet.put(thumbnail_pic, json.optString(thumbnail_pic));
    tweet.put(bmiddle_pic, json.optString(bmiddle_pic));
    tweet.put(original_pic, json.optString(original_pic));
    // ???
    if (json.has(retweeted_status)) {
        tweet.put(retweeted_status, json.optJSONObject(retweeted_status).toString());
    }
    // 
    if (json.has(User.SINGLE)) {
        tweet.put(uid, json.optJSONObject(User.SINGLE).optLong(Constants.ID));
    } else if (json.has(uid)) {
        tweet.put(uid, json.optLong(uid));
    }
    tweet.put(reposts_count, json.optInt(reposts_count));
    tweet.put(comments_count, json.optInt(comments_count));
    tweet.put(attitudes_count, json.optInt(attitudes_count));
    return tweet;
}

From source file:org.jboss.capedwarf.social.facebook.PostId.java

public void readJSONObject(JSONObject json) throws JSONException {
    String tmp = json.optString("id");
    if (tmp != null && tmp.length() > 0)
        id = tmp;/*from  w  w  w . j ava 2s .c o m*/
}

From source file:com.projectgoth.mywebrtcdemo.WebSocketRTCClient.java

@Override
public void onWebSocketMessage(final String msg) {
    if (wsClient.getState() != WebSocketConnectionState.REGISTERED) {
        Log.e(TAG, "Got WebSocket message in non registered state.");
        return;//from   w w  w  . ja v a 2s .co  m
    }
    try {
        JSONObject json = new JSONObject(msg);
        String msgText = json.getString("msg");
        String errorText = json.optString("error");
        if (msgText.length() > 0) {
            json = new JSONObject(msgText);
            String type = json.optString("type");
            if (type.equals("candidate")) {
                IceCandidate candidate = new IceCandidate(json.getString("id"), json.getInt("label"),
                        json.getString("candidate"));
                events.onRemoteIceCandidate(candidate);
            } else if (type.equals("answer")) {
                if (initiator) {
                    SessionDescription sdp = new SessionDescription(
                            SessionDescription.Type.fromCanonicalForm(type), json.getString("sdp"));
                    events.onRemoteDescription(sdp);
                } else {
                    reportError("Received answer for call initiator: " + msg);
                }
            } else if (type.equals("offer")) {
                if (!initiator) {
                    SessionDescription sdp = new SessionDescription(
                            SessionDescription.Type.fromCanonicalForm(type), json.getString("sdp"));
                    events.onRemoteDescription(sdp);
                } else {
                    reportError("Received offer for call receiver: " + msg);
                }
            } else if (type.equals("bye")) {
                events.onChannelClose();
            } else {
                reportError("Unexpected WebSocket message: " + msg);
            }
        } else {
            if (errorText != null && errorText.length() > 0) {
                reportError("WebSocket error message: " + errorText);
            } else {
                reportError("Unexpected WebSocket message: " + msg);
            }
        }
    } catch (JSONException e) {
        reportError("WebSocket message JSON parsing error: " + e.toString());
    }
}

From source file:com.leanengine.RestService.java

protected LeanEntity[] queryPrivate(final LeanQuery query) throws LeanException {
    if (!LeanAccount.isUserLoggedIn())
        throw new LeanException(LeanError.Type.NotAuthorizedError);

    String url = LeanEngine.getHostURI() + "/rest/v1/query?lean_token=" + LeanEngine.getAuthToken();

    try {//from w w w  . j  av  a2s. c o  m
        JSONObject queryJson = JsonEncode.queryToJson(query);
        JSONObject jsonObject = doPost(url, queryJson);

        // update the Query's cursor - used in fetching next results
        String cursor = jsonObject.optString("cursor");
        if (cursor.length() != 0)
            query.setCursor(cursor);

        return JsonDecode.entityListFromJson(jsonObject);
    } catch (IOException e) {
        throw new LeanException(LeanError.Type.NetworkError);
    }
}

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

public static User fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    User user = new User();
    user.id = o.optString("id");
    user.username = o.optString("username");
    user.fullName = o.optString("full_name");
    user.profilePicture = o.optString("profile_picture");
    return user;/*from  w ww.  ja v  a 2  s .  c o  m*/
}

From source file:com.richtodd.android.quiltdesign.block.QuiltDesignThumbnailProvider.java

@Override
public Bitmap getThumbnail(JSONObject object) {

    String objectType = object.optString("objectType");
    if (objectType.equals("block")) {
        try {//from   w  w w .j a  v a2  s  .co  m
            PaperPiecedBlock block = PaperPiecedBlock.createFromJSONObject(object);
            return getThumbnail(block);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    if (objectType.equals("quilt")) {
        try {
            Quilt quilt = Quilt.createFromJSONObject(object);
            return getThumbnail(quilt);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    if (objectType.equals("theme")) {
        try {
            Theme theme = Theme.createFromJSONObject(object);
            return getThumbnail(theme);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    return null;
}

From source file:com.ibm.mobilefirstplatform.clientsdk.cordovaplugins.push.CDVMFPPush.java

/**
 * Registers the device for Push notifications with the given alias and consumerId
 * @param callbackContext Javascript callback
 */// ww  w .j a  v  a2 s  .com
private void registerDevice(final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            MFPPush.getInstance().register(new MFPPushResponseListener<String>() {
                @Override
                public void onSuccess(String s) {

                    String message = s;
                    try {
                        JSONObject responseJson = new JSONObject(s.substring(s.indexOf('{')));
                        JSONObject messageJson = new JSONObject();
                        messageJson.put("token", responseJson.optString("token"));
                        messageJson.put("userId", responseJson.optString("userId"));
                        messageJson.put("deviceId", responseJson.optString("deviceId"));
                        message = messageJson.toString();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }

                    pushLogger.debug("registerDevice() Success : " + message);
                    callbackContext.success(message);
                }

                @Override
                public void onFailure(MFPPushException ex) {
                    pushLogger.debug("registerDevice() Error : " + ex.toString());
                    callbackContext.error(ex.toString());
                }
            });
        }
    });

}

From source file:com.mikecorrigan.trainscorekeeper.ActivityNewGame.java

private void addContent() {
    Log.vc(VERBOSE, TAG, "addContent");

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);

    Resources res = getResources();
    AssetManager am = res.getAssets();/*from  w w w  .  j a  v a  2s. c  o  m*/
    String files[];
    try {
        files = am.list(ASSETS_BASE);
        if (files == null || files.length == 0) {
            Log.e(TAG, "addContent: empty asset list");
            return;
        }

        for (final String file : files) {
            final String path = ASSETS_BASE + File.separator + file;

            JSONObject jsonRoot = JsonUtils.readFromAssets(this /* context */, path);
            if (jsonRoot == null) {
                Log.e(file, "addContent: failed to read read asset");
                continue;
            }

            final String name = jsonRoot.optString(JsonSpec.ROOT_NAME);
            if (TextUtils.isEmpty(name)) {
                Log.e(file, "addContent: failed to read asset name");
                continue;
            }

            final String description = jsonRoot.optString(JsonSpec.ROOT_DESCRIPTION, name);

            TextView textView = new TextView(this /* context */);
            textView.setText(name);
            linearLayout.addView(textView);

            Button button = new Button(this /* context */);
            button.setText(description);
            button.setOnClickListener(new OnRulesClickListener(path));
            linearLayout.addView(button);
        }
    } catch (IOException e) {
        Log.th(TAG, e, "addContent: asset list failed");
    }
}