Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

In this page you can find the example usage for org.json JSONArray get.

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:com.trk.aboutme.facebook.Response.java

private static List<Response> createResponsesFromObject(HttpURLConnection connection, List<Request> requests,
        Object object, boolean isFromCache) throws FacebookException, JSONException {
    assert (connection != null) || isFromCache;

    int numRequests = requests.size();
    List<Response> responses = new ArrayList<Response>(numRequests);
    Object originalResult = object;

    if (numRequests == 1) {
        Request request = requests.get(0);
        try {/*from  w  w  w .j ava  2 s.  c  o  m*/
            // Single request case -- the entire response is the result, wrap it as "body" so we can handle it
            // the same as we do in the batched case. We get the response code from the actual HTTP response,
            // as opposed to the batched case where it is returned as a "code" element.
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(BODY_KEY, object);
            int responseCode = (connection != null) ? connection.getResponseCode() : 200;
            jsonObject.put(CODE_KEY, responseCode);

            JSONArray jsonArray = new JSONArray();
            jsonArray.put(jsonObject);

            // Pretend we got an array of 1 back.
            object = jsonArray;
        } catch (JSONException e) {
            responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
        } catch (IOException e) {
            responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
        }
    }

    if (!(object instanceof JSONArray) || ((JSONArray) object).length() != numRequests) {
        FacebookException exception = new FacebookException("Unexpected number of results");
        throw exception;
    }

    JSONArray jsonArray = (JSONArray) object;

    for (int i = 0; i < jsonArray.length(); ++i) {
        Request request = requests.get(i);
        try {
            Object obj = jsonArray.get(i);
            responses.add(createResponseFromObject(request, connection, obj, isFromCache, originalResult));
        } catch (JSONException e) {
            responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
        } catch (FacebookException e) {
            responses.add(new Response(request, connection, new FacebookRequestError(connection, e)));
        }
    }

    return responses;
}

From source file:com.speedtong.example.ui.account.LoginActivity.java

private void doLoginReuqest(String user_name, String user_pwd) {
    CCPParameters ccpParameters = new CCPParameters();
    ccpParameters.setParamerTagKey("Request");
    ccpParameters.add("secret_key", "a04daaca96294836bef207594a0a4df8");
    ccpParameters.add("user_name", user_name);
    ccpParameters.add("user_pwd", user_pwd);
    AsyncECRequestRunner.requestAsyncForEncrypt(
            "https://sandboxapp.cloopen.com:8883/2013-12-26/General/GetDemoAccounts", ccpParameters, "POST",
            true, new InnerRequestListener() {

                @Override/* w ww  . java  2 s.com*/
                public void onECRequestException(CCPException arg0) {
                    ECLog4Util.e("TAG", "onECRequestException " + arg0.getMessage());
                    ToastUtil.showMessage(arg0.getMessage());
                    dismissPostingDialog();
                }

                @Override
                public void onComplete(String arg0) {
                    ECLog4Util.e("TAG", "onComplete " + arg0);
                    String json = OrgJosnUtils.xml2json(arg0);
                    if (json != null) {
                        try {
                            JSONObject mJSONObject = (JSONObject) (new JSONObject(json)).get("Response");
                            if ("000000".equals(mJSONObject.get("statusCode"))) {
                                ECLog4Util.e("TAG", "statusCode " + mJSONObject.get("statusCode"));
                                JSONObject app = (JSONObject) mJSONObject.get("Application");
                                JSONArray jarray = new JSONArray(app.get("SubAccount") + "");
                                int length = jarray.length();
                                ArrayList<ECContacts> arraylist = new ArrayList<ECContacts>();
                                for (int i = 0; i < length; i++) {
                                    JSONObject object = (JSONObject) jarray.get(i);
                                    ECContacts bean = new ECContacts(object.getString("voip_account"));
                                    bean.setToken(object.getString("voip_token"));
                                    bean.setSubAccount(object.getString("sub_account"));
                                    bean.setSubToken(object.getString("sub_token"));
                                    arraylist.add((bean));
                                }
                                saveAutoLogin();
                                Intent intent = new Intent(LoginActivity.this, AccountChooseActivity.class);
                                intent.putParcelableArrayListExtra("arraylist", arraylist);
                                intent.putParcelableArrayListExtra("arraylist", arraylist);
                                startActivityForResult(intent, 0xa);
                            } else {
                                ECLog4Util.e("TAG", "statusCode " + mJSONObject.get("statusCode"));
                                String errorMsg = mJSONObject.get("statusCode").toString();
                                if (mJSONObject.has("statusMsg")) {
                                    errorMsg = mJSONObject.get("statusMsg").toString();
                                }
                                ToastUtil.showMessage(errorMsg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastUtil.showMessage(e.getMessage());
                        }
                    }

                    dismissPostingDialog();
                }

            });
}

From source file:org.cfr.restlet.ext.shindig.resource.MakeRequestHandlerTest.java

@Test
public void testSetCookiesReturned() throws Exception {
    HttpRequest internalRequest = new HttpRequest(REQUEST_URL);
    HttpResponse response = new HttpResponseBuilder().setResponse("foo".getBytes("UTF-8"))
            .addHeader("Set-Cookie", "foo=bar; Secure").addHeader("Set-Cookie", "name=value").create();

    expect(pipeline.execute(internalRequest)).andReturn(response);
    replay();/*  w w w . j a va  2 s  .  c om*/

    handler.fetch(contextResource);
    JSONObject results = extractJsonFromResponse();
    JSONObject headers = results.getJSONObject("headers");
    assertNotNull(headers);
    JSONArray cookies = headers.getJSONArray("set-cookie");
    assertNotNull(cookies);
    assertEquals(2, cookies.length());
    assertEquals("foo=bar; Secure", cookies.get(0));
    assertEquals("name=value", cookies.get(1));
}

From source file:org.cfr.restlet.ext.shindig.resource.MakeRequestHandlerTest.java

@Test
public void testLocationReturned() throws Exception {
    HttpRequest internalRequest = new HttpRequest(REQUEST_URL);
    HttpResponse response = new HttpResponseBuilder().setResponse("foo".getBytes("UTF-8"))
            .addHeader("Location", "somewhere else").create();

    expect(pipeline.execute(internalRequest)).andReturn(response);
    replay();//from  w w w . j a  v  a  2s.  com

    handler.fetch(contextResource);
    JSONObject results = extractJsonFromResponse();
    JSONObject headers = results.getJSONObject("headers");
    assertNotNull(headers);
    JSONArray locations = headers.getJSONArray("location");
    assertNotNull(locations);
    assertEquals(1, locations.length());
    assertEquals("somewhere else", locations.get(0));
}

From source file:com.googlecode.gmaps4jsf.services.ReverseGeocoderServiceImpl.java

public PlaceMark getPlaceMark(String latitude, String longitude) throws Exception {
    try {//from   w  w  w .j  a  v  a  2s.c  o  m
        URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude.trim() + ","
                + longitude.trim() + "&sensor=false");

        PlaceMark placeMark = new PlaceMark();
        JSONObject json = new JSONObject(readURL(url));
        JSONArray results = (JSONArray) json.getJSONArray(ComponentConstants.RESULTS_LABEL);

        JSONObject placeMarkPrimaryData = (JSONObject) results.get(0);

        getPlaceMarkPrimaryInformation(placeMark, placeMarkPrimaryData);

        return placeMark;
    } catch (Exception exception) {
        throw new Exception("Error: " + exception.getMessage());
    }
}

From source file:edu.ucsb.cs.capstone.letmypeoplecode.smartrover.HttpServerTranslator.java

private void parseJson() throws IOException, JSONException {
    BufferedReader rd;/*from   w  ww .ja  v a 2s  . c  om*/
    String getParams = "&xPosition=" + myRover.getLastValidX() + "&yPosition=" + myRover.getLastValidY()
            + "&degrees=" + myRover.getHeadingDegrees();
    if (this.mainActivity != null) {
        if (this.mainActivity.getStreamVideoSwitch().isChecked()) {
            getParams += "&video_url=" + this.mainActivity.getStreamVideoAddress().getText();
        }
    }
    if (notifyTrainDone) {
        getParams += "&trainDone";
        notifyTrainDone = false;
    }
    if (!useSockets) {
        String requestURL = "http://www.letmypeoplecode.com/rover?key=letmypeoplecode" + getParams;
        HttpGet request = new HttpGet(requestURL);

        HttpResponse response = httpClient.execute(request);
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } else {
        rd = socketIn;
        socketOut.write(getParams + "\n");
        socketOut.flush();
    }
    //        long t0 = System.nanoTime();
    String line = "";
    StringBuilder str = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        if (useSockets && line.equals("f"))
            break;
        str.append(line);
    }
    String s = str.toString();
    s = s.replaceAll("\n", "\\n");
    JSONObject json;
    String message;

    try {
        json = new JSONObject(s);
        message = json.getString("messages");
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    }

    if (!enabled)
        return;

    if (message.equals("yes")) {
        JSONArray actions = json.getJSONArray("actions");
        for (int i = 0; i < actions.length(); i++) {
            String action = (String) actions.get(i);
            if (action.equals("forward")) {
                myRover.forward();
            }
            if (action.equals("reverse")) {
                myRover.reversePanic();
            }
            if (action.equals("turn_right")) {
                myRover.turnRight();
            }
            if (action.equals("turn_left")) {
                myRover.turnLeft();
            }
            if (action.equals("fork_up")) {
                myRover.forkUp();
            }
            if (action.equals("fork_down"))
                myRover.forkDown();
            if (action.equals("mirror_left")) {
                myRover.mirrorLeft();
            }
            if (action.equals("mirror_right")) {
                myRover.mirrorRight();
            }
            if (action.startsWith("move_x")) {
                String[] parts = action.split(" ");
                double x = Double.parseDouble(parts[1]);
                double y = Double.parseDouble(parts[2]);

                //Get the destination
                int go_xInInches = RoverController.convertFeetToInchesWithRounding(x);
                int go_yInInches = RoverController.convertFeetToInchesWithRounding(y);

                //Get where the rover currently is
                int currentXInInches = RoverController.convertFeetToInchesWithRounding(myRover.getLastValidX());
                int currentYInInches = RoverController.convertFeetToInchesWithRounding(myRover.getLastValidY());

                // Safety check, make sure we aren't trying to go off the map
                if ((go_xInInches / LabMap.GRID_SIZE_IN_INCHES >= myRover.getMap().getWidthInTiles())
                        || go_yInInches / LabMap.GRID_SIZE_IN_INCHES >= myRover.getMap().getHeightInTiles()) {
                    Log.i("position", "Out of bounds");
                    return;
                }

                if (myRover.getCurrentStep() != 0) {
                    Log.i("position", "Cannot select new destination until old destination has been reached.");
                    return;
                }

                // The formatting here is to make it readable since the parameters are long
                // We are calculating a new path and setting it in the rover for the navigation to handle
                myRover.setPath(myRover.getFinder().findPath(new RoverMover(LabMap.ROVER),
                        currentXInInches / LabMap.GRID_SIZE_IN_INCHES,
                        currentYInInches / LabMap.GRID_SIZE_IN_INCHES,
                        go_xInInches / LabMap.GRID_SIZE_IN_INCHES, go_yInInches / LabMap.GRID_SIZE_IN_INCHES));

                // Force the first step because the system won't do anything otherwise
                if (myRover.getPath() != null) {
                    Path.Step step = myRover.getPath().getStep(myRover.getCurrentStep());
                    myRover.setCurrentStep(myRover.getCurrentStep() + 1);

                    // Convert to feet
                    double newX = (step.getX() * LabMap.GRID_SIZE_IN_INCHES) / 12D;
                    double newY = (step.getY() * LabMap.GRID_SIZE_IN_INCHES) / 12D;
                    myRover.setDesiredX(newX);
                    myRover.setDesiredY(newY);

                    Log.i("position", "newStep: " + step.getX() + ", " + step.getY());
                }
            }
            if (action.startsWith("train")) {
                String[] parts = action.split(" ");
                try {
                    myRover.bluetoothTrain(new Point3D(parts[1], parts[2]));
                    notifyTrainDone = true;
                    if (trainDoneCallback != null)
                        trainDoneCallback.run();
                } catch (LocalizerError e) {
                    Log.w(TAG, e);
                    //TODO: Perhaps notify the web UI of an error?
                }
            }
            if (action.equals("request_video_url")) {
                if (this.mainActivity != null) {
                    // Flip the switch
                    this.mainActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            HttpServerTranslator.this.mainActivity.getStreamVideoSwitch().setChecked(
                                    HttpServerTranslator.this.mainActivity.getStreamVideoSwitch().isChecked());
                        }
                    });
                }
            }
        }
    } else {
        myRover.stop();
    }
    //        Log.i("net_speed",String.format("%.4f",(System.nanoTime()-t0)/1.0E9));
}

From source file:screenieup.PomfUpload.java

/**
 * Parse the response to get the image link.
 * @param response the image link resulting from the upload
 *///from   w  w  w  .  j  a v a2 s .c  om
private void parseResponse(String response) {
    JSONObject outerjson = new JSONObject(response);
    JSONArray jsnarray = (JSONArray) outerjson.get("files");
    JSONObject innerjson = (JSONObject) jsnarray.get(0);
    pomfurl = pomfix + innerjson.get("url").toString();
}

From source file:io.rapidpro.androidchannel.json.JSON.java

private static ArrayList arrayToList(JSONArray jsonArray) {
    try {//from   ww w. j a v  a 2s .c  o m
        ArrayList list = new ArrayList();
        for (int i = 0; i < jsonArray.length(); i++) {
            Object o = jsonArray.get(i);
            if (o instanceof JSONArray) {
                list.add(arrayToList((JSONArray) o));
            } else if (o instanceof JSONObject) {
                list.add(new JSON((JSONObject) o));
            } else {
                list.add(o);
            }
        }
        return list;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hichinaschool.flashcards.libanki.Storage.java

private static void _upgradeClozeModel(Collection col, JSONObject m) {
    try {/*from   w  ww.  ja  va 2  s.  c om*/
        m.put("type", Sched.MODEL_CLOZE);
        // convert first template
        JSONObject t = m.getJSONArray("tmpls").getJSONObject(0);
        for (String type : new String[] { "qfmt", "afmt" }) {
            t.put(type, t.getString(type).replaceAll("\\{\\{cloze:1:(.+?)\\}\\}", "{{cloze:$1}}"));
        }
        t.put("name", "Cloze");
        // delete non-cloze cards for the model
        JSONArray ja = m.getJSONArray("tmpls");
        ArrayList<JSONObject> rem = new ArrayList<JSONObject>();
        for (int i = 1; i < ja.length(); i++) {
            JSONObject ta = ja.getJSONObject(i);
            if (!ta.getString("afmt").contains("{{cloze:")) {
                rem.add(ta);
            }
        }
        for (JSONObject r : rem) {
            // TODO: write remtemplate
            col.getModels().remTemplate(m, r);
        }
        JSONArray newArray = new JSONArray();
        newArray.put(ja.get(0));
        m.put("tmpls", newArray);
        col.getModels()._updateTemplOrds(m);
        col.getModels().save(m);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Given an JSONArray retrieved from JSONObject, and the destination item
 * type, unmarshall this list to a List of given item type.
 *
 * @param jsonArr/*from w  ww .  j  ava 2s. com*/
 * @param itemType
 * @return
 */
private static List<?> JSONToList(JSONArray jsonArr, Type itemType) {
    List<Object> result = new ArrayList<Object>();

    Class<?> rawType = null;
    ParameterizedType pType = null;

    if (itemType instanceof ParameterizedType) {
        pType = (ParameterizedType) itemType;
        rawType = (Class<?>) pType.getRawType();
    } else {
        rawType = (Class<?>) itemType;
    }

    int len = jsonArr.length();
    for (int i = 0; i < len; i++) {
        try {
            Object item = jsonArr.get(i);
            Object converted = valToType(item, itemType);
            if (converted != null) {
                result.add(converted);
            }
        } catch (JSONException e) {
            throw new ParserException(e);
        }
    }

    return result;
}