Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

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

private void deserializeKey(String key, Bundle bundle) throws JSONException {
    String jsonString = cache.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }//from   www . j ava 2 s .  com
        bundle.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        bundle.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        bundle.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        bundle.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        bundle.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        bundle.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        bundle.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        bundle.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        bundle.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        bundle.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        bundle.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        bundle.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        bundle.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            bundle.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        bundle.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        bundle.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        bundle.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            bundle.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
        } catch (IllegalArgumentException e) {
        }
    }
}

From source file:org.mixare.data.convert.WikiDataProcessor.java

@Override
public List<Marker> load(String rawData, int taskId, int colour) throws JSONException {
    List<Marker> markers = new ArrayList<Marker>();
    JSONObject root = convertToJSON(rawData);
    JSONArray dataArray = root.getJSONArray("geonames");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    for (int i = 0; i < top; i++) {
        JSONObject jo = dataArray.getJSONObject(i);

        Marker ma = null;// w  w w. j a  v a2  s  .c  o m
        if (jo.has("title") && jo.has("lat") && jo.has("lng") && jo.has("elevation")
                && jo.has("wikipediaUrl")) {

            Log.v(MixView.TAG, "processing Wikipedia JSON object");

            //no unique ID is provided by the web service according to http://www.geonames.org/export/wikipedia-webservice.html
            ma = new POIMarker("", HtmlUnescape.unescapeHTML(jo.getString("title"), 0), jo.getDouble("lat"),
                    jo.getDouble("lng"), jo.getDouble("elevation"), "http://" + jo.getString("wikipediaUrl"),
                    taskId, colour);
            markers.add(ma);
        }
    }
    return markers;
}

From source file:com.skalski.raspberrycontrol.Activity_TempSensors.java

Handler getClientHandler() {

    return new Handler() {
        @Override/*from w  w  w .ja v a 2 s .  co m*/
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            JSONArray tempsensors;
            tempsensorsArray = new ArrayList<Custom_TempSensorsAdapter>();
            tempsensorsLayout.setRefreshing(false);

            Log.i(LOGTAG, LOGPREFIX + "new message received from server");

            try {

                root = new JSONObject(msg.obj.toString());

                if (root.has(TAG_ERROR)) {

                    String err = getResources().getString(R.string.com_msg_3) + root.getString(TAG_ERROR);
                    toast_connection_error(err);

                } else {

                    tempsensors = root.getJSONArray(TAG_TEMPSENSORS);

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

                        JSONObject tempsensor = tempsensors.getJSONObject(i);

                        String type = tempsensor.getString(TAG_TYPE);
                        String id = tempsensor.getString(TAG_ID);
                        String crc = tempsensor.getString(TAG_CRC);

                        float temp = (float) tempsensor.getDouble(TAG_TEMP);
                        String tempstr = String.format("%.3f", temp);

                        if (tempstr != null)
                            tempstr = tempstr + " \u2103";

                        tempsensorsArray.add(new Custom_TempSensorsAdapter(type, id, tempstr, crc));
                    }

                    if (tempsensors.length() == 0) {
                        Log.w(LOGTAG, LOGPREFIX + "can't find 1-wire temperature sensors");
                        toast_connection_error(getResources().getString(R.string.error_msg_7));
                    }
                }

            } catch (Exception ex) {
                Log.e(LOGTAG, LOGPREFIX + "received invalid JSON object");
                toast_connection_error(getResources().getString(R.string.error_msg_2));
            }

            setListAdapter(new Custom_TempSensorsArrayAdapter(getApplicationContext(), tempsensorsArray));
        }
    };
}

From source file:org.openmrs.mobile.listeners.findPatients.LastViewedPatientListener.java

@Override
public void onResponse(JSONObject response) {
    List<Patient> patientsList = new ArrayList<Patient>();
    mLogger.d(response.toString());/*w ww  . j a v a2 s  .  c o m*/

    try {
        JSONArray patientsJSONList = response.getJSONArray(BaseManager.RESULTS_KEY);
        for (int i = 0; i < patientsJSONList.length(); i++) {
            patientsList.add(PatientMapper.map(patientsJSONList.getJSONObject(i)));
        }

        refreshFragment(patientsList, FindPatientsActivity.FragmentMethod.Update);

    } catch (JSONException e) {
        mLogger.d(e.toString());
        refreshFragment(null, FindPatientsActivity.FragmentMethod.StopLoader);
    }
}

From source file:org.akvo.caddisfly.helper.TestConfigHelper.java

private static TestInfo loadTest(JSONObject item) {

    TestInfo testInfo = null;/*from   w ww. jav  a2  s  .  c o m*/
    try {
        //Get the test type
        TestType type;
        if (item.has("subtype")) {
            switch (item.getString("subtype")) {
            case "liquid-chamber":
                type = TestType.COLORIMETRIC_LIQUID;
                break;
            case "strip":
            case "striptest":
                type = TestType.COLORIMETRIC_STRIP;
                break;
            case "sensor":
                type = TestType.SENSOR;
                break;
            default:
                return null;
            }
        } else {
            return null;
        }

        //Get the name for this test
        String name = item.getString("name");

        //Load results
        JSONArray resultsArray = null;
        if (item.has("results")) {
            resultsArray = item.getJSONArray("results");
        }

        //Load the dilution percentages
        String dilutions = "0";
        if (item.has("dilutions")) {
            dilutions = item.getString("dilutions");
            if (dilutions.isEmpty()) {
                dilutions = "0";
            }
        }
        String[] dilutionsArray = dilutions.split(",");

        //Load the ranges
        String ranges = "0";
        if (item.has("ranges")) {
            ranges = item.getString("ranges");
        }

        String[] rangesArray = ranges.split(",");

        String[] defaultColorsArray = new String[0];
        if (item.has("defaultColors")) {
            String defaultColors = item.getString("defaultColors");
            defaultColorsArray = defaultColors.split(",");
        }

        // get uuids
        String uuid = item.getString(SensorConstants.UUID);

        testInfo = new TestInfo(name, type, rangesArray, defaultColorsArray, dilutionsArray, uuid,
                resultsArray);

        testInfo.setHueTrend(item.has("hueTrend") ? item.getInt("hueTrend") : 0);

        testInfo.setDeviceId(item.has("deviceId") ? item.getString("deviceId") : "Unknown");

        testInfo.setResponseFormat(item.has("responseFormat") ? item.getString("responseFormat") : "");

        testInfo.setUseGrayScale(item.has("grayScale") && item.getBoolean("grayScale"));

        testInfo.setMonthsValid(item.has("monthsValid") ? item.getInt("monthsValid") : DEFAULT_MONTHS_VALID);

        //if calibrate not specified then default to false otherwise use specified value
        testInfo.setRequiresCalibration(item.has("calibrate") && item.getBoolean("calibrate"));

        testInfo.setIsDeprecated(item.has("deprecated") && item.getBoolean("deprecated"));

    } catch (JSONException e) {
        Timber.e(e);
    }

    return testInfo;
}

From source file:pe.chalk.takoyaki.target.NaverCafe.java

public NaverCafe(JSONObject properties) {
    super(properties.getString("prefix"), properties.getLong("interval"));
    this.getFilters()
            .addAll(Utils.buildStream(String.class, properties.getJSONArray("filters")).map(filterName -> {
                switch (filterName) {
                case ArticleFilter.NAME:
                    return new ArticleFilter(this);

                case CommentaryFilter.NAME:
                    return new CommentaryFilter(this);

                case VisitationFilter.NAME:
                    return new VisitationFilter(this);

                default:
                    return null;
                }//from   w  w w  .  j  a  va 2 s  .  co m
            }).filter(filter -> filter != null).collect(Collectors.toList()));

    this.staff = new Staff(this.getLogger(), properties.getInt("timeout"),
            properties.getJSONObject("naverAccount"));
    this.address = properties.getString("address");
    this.contentUrl = String.format(STRING_CONTENT, this.getAddress());

    try {
        Document contentDocument = Jsoup.parse(this.getStaff().parse(this.contentUrl));
        this.setName(contentDocument.select("h1.d-none").text());

        Matcher clubIdMatcher = NaverCafe.PATTERN_CLUB_ID
                .matcher(contentDocument.head().select("script:not([type]):not([src])").first().html());
        if (!clubIdMatcher.find()) {
            throw new IllegalArgumentException(" ID ?  : " + this.getName());
        }

        this.clubId = Integer.parseInt(clubIdMatcher.group(1));
        this.menus = contentDocument.select("a[id^=menuLink]").stream()
                .map(element -> new Menu(this, Integer.parseInt(element.id().substring(8)), element.text()))
                .collect(Collectors.toList());

        this.articleUrl = String.format(STRING_ARTICLE, this.getClubId());

        Files.write(Paths.get("Takoyaki-menus-" + this.getAddress() + ".log"),
                this.getMenus().stream().map(Menu::toString).collect(Collectors.toList()),
                StandardCharsets.UTF_8);
    } catch (IOException | JSONException e) {
        String errorMessage = "?? : " + e.getClass().getName() + ": "
                + e.getMessage();

        this.getLogger().error(errorMessage);
        throw new IllegalStateException(errorMessage);
    }
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse enroll(String jsonRequest, OxPush2Request oxPush2Request, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    if (request.has("registerRequests")) {
        JSONArray registerRequestArray = request.getJSONArray("registerRequests");
        if (registerRequestArray.length() == 0) {
            throw new U2FException("Failed to get registration request!");
        }//  w w  w . ja v a2s .  co  m
        request = (JSONObject) registerRequestArray.get(0);
    }

    if (!request.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
        throw new U2FException("Unsupported U2F_V2 version!");
    }

    String version = request.getString(JSON_PROPERTY_VERSION);
    String appParam = request.getString(JSON_PROPERTY_APP_ID);
    String challenge = request.getString(JSON_PROPERTY_SERVER_CHALLENGE);
    String origin = oxPush2Request.getIssuer();

    EnrollmentResponse enrollmentResponse = u2fKey
            .register(new EnrollmentRequest(version, appParam, challenge, oxPush2Request));
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Enrollment response: " + enrollmentResponse);

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REGISTER_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_REGISTER);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, challenge);
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeRegisterResponse(enrollmentResponse);

    String deviceType = getDeviceType();
    String versionName = getVersionName();

    DeviceData deviceData = new DeviceData();
    deviceData.setUuid(DeviceUuidManager.getDeviceUuid(context).toString());
    deviceData.setPushToken(PushNotificationManager.getRegistrationId(context));
    deviceData.setType(deviceType);
    deviceData.setPlatform("android");
    deviceData.setName(Build.MODEL);
    deviceData.setOsName(versionName);
    deviceData.setOsVersion(Build.VERSION.RELEASE);

    String deviceDataString = new Gson().toJson(deviceData);

    JSONObject response = new JSONObject();
    response.put("registrationData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("deviceData", Utils.base64UrlEncode(deviceDataString.getBytes(Charset.forName("ASCII"))));

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(new String(challenge));
    tokenResponse.setKeyHandle(new String(enrollmentResponse.getKeyHandle()));

    return tokenResponse;
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Starting to process sign request: " + jsonRequest);
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    JSONArray authenticateRequestArray = null;
    if (request.has("authenticateRequests")) {
        authenticateRequestArray = request.getJSONArray("authenticateRequests");
        if (authenticateRequestArray.length() == 0) {
            throw new U2FException("Failed to get authentication request!");
        }//from  w  w  w  . ja va2  s  .  c o m
    } else {
        authenticateRequestArray = new JSONArray();
        authenticateRequestArray.put(request);
    }

    Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests");

    AuthenticateResponse authenticateResponse = null;
    String authenticatedChallenge = null;
    JSONObject authRequest = null;
    for (int i = 0; i < authenticateRequestArray.length(); i++) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Process authentication request: " + authRequest);
        authRequest = (JSONObject) authenticateRequestArray.get(i);

        if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
            throw new U2FException("Unsupported U2F_V2 version!");
        }

        String version = authRequest.getString(JSON_PROPERTY_VERSION);
        String appParam = authRequest.getString(JSON_PROPERTY_APP_ID);
        String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE);
        byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE),
                Base64.URL_SAFE | Base64.NO_WRAP);

        authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version,
                AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Authentication response: " + authenticateResponse);
        if (authenticateResponse != null) {
            authenticatedChallenge = challenge;
            break;
        }
    }

    if (authenticateResponse == null) {
        return null;
    }

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE));
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE);
    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse);

    JSONObject response = new JSONObject();
    response.put("signatureData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("keyHandle", keyHandle);

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(authenticatedChallenge);
    tokenResponse.setKeyHandle(keyHandle);

    return tokenResponse;
}

From source file:com.hichinaschool.flashcards.anki.CardEditor.java

private void setNote(Note note) {
    try {/*from w ww.j  a  v a  2 s  .  c  o  m*/
        if (note == null) {
            mCurrentDid = mCol.getDecks().current().getLong("id");
            if (mCol.getDecks().isDyn(mCurrentDid)) {
                mCurrentDid = 1;
            }

            JSONObject model = mCol.getModels().current();
            mEditorNote = new Note(mCol, model);
            mEditorNote.model().put("did", mCurrentDid);
            mModelButton.setText(getResources().getString(R.string.CardEditorModel, model.getString("name")));
            JSONArray tags = model.getJSONArray("tags");
            for (int i = 0; i < tags.length(); i++) {
                mEditorNote.addTag(tags.getString(i));
            }
        } else {
            mEditorNote = note;
            mCurrentDid = mCurrentEditedCard.getDid();
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    mCurrentTags = mEditorNote.getTags();
    updateDeck();
    updateTags();
    populateEditFields();
    swapText(true);
}

From source file:com.snappy.couchdb.CouchDBHelper.java

/**
 * Parse a single user JSON object/*  www.  j  a v a  2s .  c o m*/
 * 
 * @param json
 * @return
 * @throws JSONException
 */
public static User parseSingleUserObject(JSONObject json) throws JSONException {
    User user = null;
    ArrayList<String> contactsIds = new ArrayList<String>();

    if (json != null) {

        if (json.has(Const.ERROR)) {
            appLogout(null, false, isInvalidToken(json));
            return null;
        }

        JSONArray rows = json.getJSONArray(Const.ROWS);
        JSONObject row = rows.getJSONObject(0);
        JSONObject userJson = row.getJSONObject(Const.VALUE);

        user = sGsonExpose.fromJson(userJson.toString(), User.class);

        if (userJson.has(Const.FAVORITE_GROUPS)) {
            JSONArray favorite_groups = userJson.getJSONArray(Const.FAVORITE_GROUPS);

            List<String> groups = new ArrayList<String>();

            for (int i = 0; i < favorite_groups.length(); i++) {
                groups.add(favorite_groups.getString(i));
            }

            user.setGroupIds(groups);
        }

        if (userJson.has(Const.CONTACTS)) {
            JSONArray contacts = userJson.getJSONArray(Const.CONTACTS);

            for (int i = 0; i < contacts.length(); i++) {
                contactsIds.add(contacts.getString(i));
            }

            user.setContactIds(contactsIds);
        }
    }

    return user;
}