Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:gov.sfmta.sfpark.MyAnnotation.java

/** Populate the rate fields: rq,rate,beg,end
 *
 * @return line color associated with price at this time; or red if restricted.
 *///from  www  .j a  v  a 2s.c  o m
int fetchRates() throws JSONException {
    int lineColor = grey;

    if (allGarageData.has(RATES_KEY)) {
        JSONObject rates = allGarageData.getJSONObject(RATES_KEY);
        // Get an optional JSONArray associated with a key. It
        // returns null if there is no such key, or if its
        // value is not a JSONArray.
        JSONArray rateArray = rates.optJSONArray(RS_KEY);
        if (!(rateArray == null)) {
            int rsc = rateArray.length();
            for (int i = 0; i < rsc; i++) {
                JSONObject rateObject = rateArray.getJSONObject(i);
                rateStructureHandle(rateObject);
                if (inThisBucketBegin(beg, end)) {
                    lineColor = bucketFinder(Float.parseFloat(rate));
                    break;
                }
            }
        } else {
            JSONObject rateObject = rates.optJSONObject(RS_KEY);
            if (!(rateObject == null)) {
                rateStructureHandle(rateObject);
                if (inThisBucketBegin(beg, end)) {
                    lineColor = bucketFinder(Float.parseFloat(rate));
                }
            } else {
                Log.v(TAG, "Fail... rateStructure isn't a dictionary or array.");
            }
        }
    } else {
        Log.v(TAG, "Fail... No rate information...");
    }

    // Restricted is always RED.
    if (NOPARKING_SET.contains(rq)) {
        lineColor = grey;
    }

    return lineColor;
}

From source file:org.uiautomation.ios.wkrdp.internal.WebKitRemoteDebugProtocol.java

public synchronized JSONObject sendWebkitCommand(JSONObject command, int pageId) {
    String sender = generateSenderString(pageId);
    try {//from  ww w  .  j a v a2 s .  c  o m
        commandId++;
        command.put("id", commandId);

        long start = System.currentTimeMillis();

        String xml = plist.JSONCommand(command);
        Map<String, String> var = ImmutableMap.of("$WIRConnectionIdentifierKey", connectionId, "$bundleId",
                bundleId, "$WIRSenderKey", sender, "$WIRPageIdentifierKey", "" + pageId);
        for (String key : var.keySet()) {
            xml = xml.replace(key, var.get(key));
        }
        sendMessage(xml);
        JSONObject response = handler.getResponse(command.getInt("id"));
        JSONObject error = response.optJSONObject("error");
        if (error != null) {
            throw new RemoteExceptionException(error, command);
        } else if (response.optBoolean("wasThrown", false)) {
            throw new WebDriverException("remote JS exception " + response.toString(2));
        } else {
            log.fine(System.currentTimeMillis() + "\t\t" + (System.currentTimeMillis() - start) + "ms\t"
                    + command.getString("method") + " " + command);
            JSONObject res = response.getJSONObject("result");
            if (res == null) {
                System.err.println("GOT a null result from " + response.toString(2));
            }
            return res;
        }
    } catch (JSONException e) {
        throw new WebDriverException(e);
    }
}

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

public static Media fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Media media = new Media();
    media.id = o.optString("id");
    media.type = o.optString("type");
    media.createdTime = o.optString("created_time");
    media.attribution = o.optString("attribution");
    media.image = Image.fromJSON(o.optJSONObject("images"));
    if (media.type.equals("video"))
        media.video = Video.fromJSON(o.optJSONObject("videos"));
    media.link = o.optString("link");
    media.filter = o.optString("filter");
    media.userHasLiked = o.optBoolean("user_has_liked");
    media.user = User.fromJSON(o.optJSONObject("user"));
    JSONArray tagsJSONArray = o.optJSONArray("tags");
    ArrayList<String> tags = new ArrayList<>();
    for (int j = 0; j < tagsJSONArray.length(); j++) {
        tags.add(tagsJSONArray.optString(j));
    }//from   ww  w. j av a 2 s.  c o m
    media.tags.addAll(tags);
    JSONArray likesJSONArray = o.optJSONObject("likes").optJSONArray("data");
    ArrayList<Like> likes = new ArrayList<>();
    for (int j = 0; j < likesJSONArray.length(); j++) {
        JSONObject likeJSON = (JSONObject) likesJSONArray.get(j);
        likes.add(Like.fromJSON(likeJSON));
    }
    media.likes.addAll(likes);
    JSONArray commentJSONArray = o.optJSONObject("comments").optJSONArray("data");
    ArrayList<Comment> comments = new ArrayList<>();
    for (int j = 0; j < commentJSONArray.length(); j++) {
        JSONObject commentJSON = (JSONObject) commentJSONArray.get(j);
        comments.add(Comment.fromJSON(commentJSON));
    }
    media.comments.addAll(comments);
    JSONArray usersInPhotoJSON = o.optJSONArray("users_in_photo");
    ArrayList<UserInPhoto> usersInPhotos = new ArrayList<>();
    for (int j = 0; j < usersInPhotoJSON.length(); j++) {
        JSONObject userInPhotoJSON = (JSONObject) usersInPhotoJSON.get(j);
        usersInPhotos.add(UserInPhoto.fromJSON(userInPhotoJSON));
    }
    media.usersInPhoto.addAll(usersInPhotos);
    JSONObject locationJSON = o.optJSONObject("location");
    if (locationJSON != null) {
        media.location = Location.fromJSON(locationJSON);
    }
    JSONObject captionJSON = o.optJSONObject("caption");
    if (captionJSON != null) {
        media.caption = Comment.fromJSON(captionJSON);
    }
    return media;
}

From source file:kr.ac.cau.mecs.cass.processor.CASLaunchProcessor.java

@Override
public Signal process(Signal signal) {
    Signal resignal = new Signal();

    resignal.setReceiver(signal.getSender());
    resignal.setSender("CASS");
    resignal.setAction(new Action(Action.ACT_LAUNCH));

    if (currentUser != null) {
        JSONObject jobj = (JSONObject) signal.getPayload().getPayload().getData();

        System.out.println(jobj.toString());

        JSONObject jcau = jobj.optJSONObject("cau");
        JSONObject jaction = jobj.optJSONObject("action");
        JSONArray jsensor = jobj.optJSONArray("sensor");

        CAUEntity cau = CAUEntity.fromJSONObject(jcau);
        ActionEntity action = ActionEntity.fromJSONObject(jaction);

        //see if user already has cau entry of that name
        DBCAUEntity dbcau = findCAU(cau.getName(), cau.getVersion());
        if (dbcau == null) {
            //create new cau here!
            dbcau = new DBCAUEntity();
            dbcau.setName(cau.getName());
            dbcau.setVersion(cau.getVersion());
            dbcau.setUser(currentUser);//from w  ww . ja  va 2s .c  om
            dbcau.setActions(new HashSet<DBActionEntity>());
        }

        //see if cau has that action already
        DBActionEntity dbaction = null;

        for (DBActionEntity tmp : dbcau.getActions()) {
            if (tmp.getAid() == action.getAid()) {
                dbaction = tmp;
                break;
            }
        }
        //create new action here!
        if (dbaction == null) {
            dbaction = new DBActionEntity();
            dbaction.setAid(action.getAid());
            dbaction.setCau(dbcau);
            dbaction.setName(action.getName());
            dbaction.setSensordata(new HashSet<DBSensorEntity>());
        }

        //create new sensor entry

        for (int i = 0; i < jsensor.length(); i++) {
            SensorEntity sensor = SensorEntity.fromJSONObject(jsensor.getJSONObject(i));
            DBSensorEntity dbsensor = new DBSensorEntity();

            dbsensor.setAction(dbaction);
            dbsensor.setDataType(sensor.getDataType());
            dbsensor.setCaeType(sensor.getCaeType());
            dbsensor.setSensorName(sensor.getSensorName());
            dbsensor.setTimestamp(sensor.getTimestamp());
            dbsensor.setValue(sensor.getValue());

            session.saveOrUpdate(dbsensor);
        }
        session.saveOrUpdate(dbcau);
        session.saveOrUpdate(dbaction);

    } else {
        setGenericMessage(resignal, "invalid credential");
    }

    return resignal;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitResetTest.java

@Test
public void testResetBadType() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "hello");

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);/*from   w ww . ja v a  2  s. c om*/

    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

    WebRequest request = getPostGitIndexRequest(gitIndexUri, null, null, "BAD");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

From source file:com.github.mhendred.face4j.model.Face.java

public Face(JSONObject jObj) throws JSONException {
    tid = jObj.getString("tid");
    label = jObj.optString("label");

    confirmed = jObj.getBoolean("confirmed");
    manual = jObj.getBoolean("manual");

    width = (float) jObj.getDouble("width");
    height = (float) jObj.getDouble("height");

    yaw = (float) jObj.getDouble("yaw");
    roll = (float) jObj.getDouble("roll");
    pitch = (float) jObj.getDouble("pitch");

    threshold = jObj.optInt("threshold");

    center = fromJson(jObj.optJSONObject("center"));

    leftEye = fromJson(jObj.optJSONObject("eye_left"));
    rightEye = fromJson(jObj.optJSONObject("eye_right"));

    leftEar = fromJson(jObj.optJSONObject("ear_left"));
    rightEar = fromJson(jObj.optJSONObject("ear_right"));

    chin = fromJson(jObj.optJSONObject("chin"));

    mouthCenter = fromJson(jObj.optJSONObject("mouth_center"));
    mouthRight = fromJson(jObj.optJSONObject("mouth_right"));
    mouthLeft = fromJson(jObj.optJSONObject("mouth_left"));

    nose = fromJson(jObj.optJSONObject("nose"));

    guesses = Guess.fromJsonArray(jObj.optJSONArray("uids"));

    // Attributes
    jObj = jObj.getJSONObject("attributes");

    if (jObj.has("smiling"))
        smiling = jObj.getJSONObject("smiling").getBoolean("value");

    if (jObj.has("glasses"))
        glasses = jObj.getJSONObject("glasses").getBoolean("value");

    if (jObj.has("gender"))
        gender = Gender.valueOf(jObj.getJSONObject("gender").getString("value"));

    if (jObj.has("mood"))
        mood = jObj.getJSONObject("mood").getString("value");

    if (jObj.has("lips"))
        lips = jObj.getJSONObject("lips").getString("value");

    if (jObj.has("age-est"))
        ageEst = jObj.getJSONObject("age-est").getInt("vaule");

    if (jObj.has("age-min"))
        ageMin = jObj.getJSONObject("age-min").getInt("vaule");

    if (jObj.has("age-max"))
        ageMax = jObj.getJSONObject("age-max").getInt("vaule");

    faceConfidence = jObj.getJSONObject("face").getInt("confidence");

    faceRect = new Rect(center, width, height);
}

From source file:com.ibm.mobilefirst.mobileedge.interpretation.Classification.java

private void executeClassification() {

    if (accelerometerData.size() >= DATA_SIZE && gyroscopeData.size() >= DATA_SIZE) {

        JSONArray accelerometerArray = getNextDataAsJSONArray(accelerometerData);
        JSONArray gyroscopeArray = getNextDataAsJSONArray(gyroscopeData);

        JSONObject params = new JSONObject();

        try {/*from   www  .  ja  va2s.  com*/
            params.put("accelerometer", accelerometerArray);
            params.put("gyroscope", gyroscopeArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject result = JSEngine.getInstance().executeFunction("detectGesture", params);

        if (result.has("detected") && result.optBoolean("detected")) {
            //notify the detected gesture
            notifyResult(result.optJSONObject("additionalInfo"));
        }
    }
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse account value./*from  ww w  .ja va  2 s  .c om*/
 * 
 * @param jsonNewAccount
 * @param acnt
 */
protected static void parseAccountValues(JSONObject jsonNewAccount, Account acnt) {
    JSONArray jsonPeriodBudgetList = jsonNewAccount.optJSONArray("periodBudget");
    JSONArray jsonPeriodValueList = jsonNewAccount.optJSONArray("periodValue");
    if (jsonPeriodBudgetList != null) {
        for (int j = 0; j < jsonPeriodBudgetList.length(); j++) {
            JSONObject jsonPeriodBudget = jsonPeriodBudgetList.getJSONObject(j);
            acnt.setBudget(jsonPeriodBudget.getString("periodId"), jsonPeriodBudget.getDouble("budget"));
        }
    }
    if (jsonPeriodValueList != null) {
        for (int j = 0; j < jsonPeriodValueList.length(); j++) {
            JSONObject jsonPeriodValue = jsonPeriodValueList.getJSONObject(j);
            acnt.setValue(jsonPeriodValue.getString("periodId"),
                    parseValue(jsonPeriodValue.optJSONObject("value")));

        }
    }
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse periods.//from w  w  w.  j  a  va 2s .co  m
 * 
 * @param jsonList
 * @param periodList
 * @param book
 */
protected static void parsePeriods(JSONArray jsonList, List<Period> periodList, Book book) {
    for (int i = 0; i < jsonList.length(); i++) {
        JSONObject jsonPeriod = jsonList.getJSONObject(i);
        Period newPeriod = new Period(Formatter.parseDate(jsonPeriod.getString("date")));
        newPeriod.setId(jsonPeriod.getString("id"));
        newPeriod.setValue(parseValue(jsonPeriod.optJSONObject("value")));
        parseTransactions(jsonPeriod.optJSONArray("transactions"), newPeriod.getTransactions(), book);
        periodList.add(newPeriod);
    }
}

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

public static JSONObject openObject(JSONObject object, String key) {
    JSONObject result;//from w  ww . j  a v a 2s  . c o  m
    try {
        result = object.optJSONObject(key);
        if (result == null) {
            result = new JSONObject();
            object.put(key, result);
        }
    } catch (JSONException e) {
        throw new AssertionError(e);
    }
    return result;
}