Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get JSONObject from jsonData/*from  w w  w .j av a  2s. co  m*/
 *
 * @param jsonData
 * @param defaultValue
 * @param keyArray
 * @return <ul>
 * <li>if jsonData is null, return defaultValue</li>
 * <li>if keyArray is null or empty, return defaultValue</li>
 * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is
 * null, return directly</li>
 * </ul>
 */
public static JSONObject getJSONObjectCascade(String jsonData, JSONObject defaultValue, String... keyArray) {
    if (StringUtils.isEmpty(jsonData)) {
        return defaultValue;
    }

    try {
        JSONObject jsonObject = new JSONObject(jsonData);
        return getJSONObjectCascade(jsonObject, defaultValue, keyArray);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get JSONArray from jsonData/*www .j  a va2s . c om*/
 *
 * @param jsonData
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li>
 * <li>return {@link JSONUtils#getJSONArray(JSONObject, String, JSONObject)}</li>
 * </ul>
 */
public static JSONArray getJSONArray(String jsonData, String key, JSONArray defaultValue) {
    if (StringUtils.isEmpty(jsonData)) {
        return defaultValue;
    }

    try {
        JSONObject jsonObject = new JSONObject(jsonData);
        return getJSONArray(jsonObject, key, defaultValue);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get Boolean from jsonData//w  w w.j av  a2 s.  co  m
 *
 * @param jsonData
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li>
 * <li>return {@link JSONUtils#getBoolean(JSONObject, String, Boolean)}</li>
 * </ul>
 */
public static boolean getBoolean(String jsonData, String key, Boolean defaultValue) {
    if (StringUtils.isEmpty(jsonData)) {
        return defaultValue;
    }

    try {
        JSONObject jsonObject = new JSONObject(jsonData);
        return getBoolean(jsonObject, key, defaultValue);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get map from jsonData.//from w w w.  j  av a 2 s .c  o  m
 *
 * @param jsonData key-value pairs string
 * @param key
 * @return <ul>
 * <li>if jsonData is null, return null</li>
 * <li>if jsonData length is 0, return empty map</li>
 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return null</li>
 * <li>return {@link JSONUtils#getMap(JSONObject, String)}</li>
 * </ul>
 */
public static Map<String, String> getMap(String jsonData, String key) {

    if (jsonData == null) {
        return null;
    }
    if (jsonData.length() == 0) {
        return new HashMap<String, String>();
    }

    try {
        JSONObject jsonObject = new JSONObject(jsonData);
        return getMap(jsonObject, key);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return null;
    }
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value
 *
 * @param source key-value pairs json/*from w  w  w.j a va2 s . co  m*/
 * @return <ul>
 * <li>if source is null or source's length is 0, return empty map</li>
 * <li>if source {@link JSONObject#JSONObject(String)} exception, return null</li>
 * <li>return {@link JSONUtils#parseKeyAndValueToMap(JSONObject)}</li>
 * </ul>
 */
public static Map<String, String> parseKeyAndValueToMap(String source) {
    if (StringUtils.isEmpty(source)) {
        return null;
    }

    try {
        JSONObject jsonObject = new JSONObject(source);
        return parseKeyAndValueToMap(jsonObject);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return null;
    }
}

From source file:at.alladin.rmbt.qos.QoSUtil.java

/**
 * /*from  w  w  w  . j  a v a 2  s . co  m*/
 * @param settings
 * @param conn
 * @param answer
 * @param lang
 * @param errorList
 * @throws SQLException 
 * @throws JSONException 
 * @throws HstoreParseException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
public static void evaluate(final ResourceBundle settings, final Connection conn, final TestUuid uuid,
        final JSONObject answer, String lang, final ErrorList errorList) throws SQLException,
        HstoreParseException, JSONException, IllegalArgumentException, IllegalAccessException {
    // Load Language Files for Client

    final List<String> langs = Arrays.asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

    if (langs.contains(lang)) {
        errorList.setLanguage(lang);
    } else {
        lang = settings.getString("RMBT_DEFAULT_LANGUAGE");
    }

    if (conn != null) {

        final Client client = new Client(conn);
        final Test test = new Test(conn);

        boolean necessaryDataAvailable = false;

        if (uuid != null && uuid.getType() != null && uuid.getUuid() != null) {
            switch (uuid.getType()) {
            case OPEN_TEST_UUID:
                if (test.getTestByOpenTestUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            case TEST_UUID:
                if (test.getTestByUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            }
        }

        final long timeStampFullEval = System.currentTimeMillis();

        if (necessaryDataAvailable) {

            final Locale locale = new Locale(lang);
            final ResultOptions resultOptions = new ResultOptions(locale);
            final JSONArray resultList = new JSONArray();

            QoSTestResultDao resultDao = new QoSTestResultDao(conn);
            List<QoSTestResult> testResultList = resultDao.getByTestUid(test.getUid());
            if (testResultList == null || testResultList.isEmpty()) {
                throw new UnsupportedOperationException("test " + test + " has no result list");
            }
            //map that contains all test types and their result descriptions determined by the test result <-> test objectives comparison
            Map<TestType, TreeSet<ResultDesc>> resultKeys = new HashMap<>();

            //test description set:
            Set<String> testDescSet = new TreeSet<>();
            //test summary set:
            Set<String> testSummarySet = new TreeSet<>();

            //Staring timestamp for evaluation time measurement
            final long timeStampEval = System.currentTimeMillis();

            //iterate through all result entries
            for (final QoSTestResult testResult : testResultList) {

                //reset test counters
                testResult.setFailureCounter(0);
                testResult.setSuccessCounter(0);

                //get the correct class of the result;
                TestType testType = null;
                try {
                    testType = TestType.valueOf(testResult.getTestType().toUpperCase(Locale.US));
                } catch (IllegalArgumentException e) {
                    final String errorMessage = "WARNING: QoS TestType '"
                            + testResult.getTestType().toUpperCase(Locale.US)
                            + "' not supported by ControlServer. Test with UID: " + testResult.getUid()
                            + " skipped.";
                    System.out.println(errorMessage);
                    errorList.addErrorString(errorMessage);
                    testType = null;
                }

                if (testType == null) {
                    continue;
                }

                Class<? extends AbstractResult<?>> clazz = testType.getClazz();
                //parse hstore data
                final JSONObject resultJson = new JSONObject(testResult.getResults());
                AbstractResult<?> result = QoSUtil.HSTORE_PARSER.fromJSON(resultJson, clazz);
                result.setResultJson(resultJson);

                if (result != null) {
                    //add each test description key to the testDescSet (to fetch it later from the db)
                    if (testResult.getTestDescription() != null) {
                        testDescSet.add(testResult.getTestDescription());
                    }
                    if (testResult.getTestSummary() != null) {
                        testSummarySet.add(testResult.getTestSummary());
                    }
                    testResult.setResult(result);

                }

                //compare test results
                compareTestResults(testResult, result, resultKeys, testType, resultOptions);

                //resultList.put(testResult.toJson());

                //save all test results after the success and failure counters have been set
                //resultDao.updateCounter(testResult);
            }

            //ending timestamp for evaluation time measurement
            final long timeStampEvalEnd = System.currentTimeMillis();

            //-------------------------------------------------------------
            //fetch all result strings from the db
            QoSTestDescDao descDao = new QoSTestDescDao(conn, locale);

            //FIRST: get all test descriptions
            Set<String> testDescToFetchSet = testDescSet;
            testDescToFetchSet.addAll(testSummarySet);

            Map<String, String> testDescMap = descDao.getAllByKeyToMap(testDescToFetchSet);

            for (QoSTestResult testResult : testResultList) {

                //and set the test results + put each one to the result list json array
                String preParsedDesc = testDescMap.get(testResult.getTestDescription());
                if (preParsedDesc != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestDescription()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestDescription(description);
                }

                //do the same for the test summary:
                String preParsedSummary = testDescMap.get(testResult.getTestSummary());
                if (preParsedSummary != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestSummary()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestSummary(description);
                }

                resultList.put(testResult.toJson(uuid.getType()));
            }

            //finally put results to json
            answer.put("testresultdetail", resultList);

            JSONArray resultDescArray = new JSONArray();

            //SECOND: fetch all test result descriptions 
            for (TestType testType : resultKeys.keySet()) {
                TreeSet<ResultDesc> descSet = resultKeys.get(testType);
                //fetch results to same object
                descDao.loadToTestDesc(descSet);

                //another tree set for duplicate entries:
                //TODO: there must be a better solution 
                //(the issue is: compareTo() method returns differnt values depending on the .value attribute (if it's set or not))
                TreeSet<ResultDesc> descSetNew = new TreeSet<>();
                //add fetched results to json

                for (ResultDesc desc : descSet) {
                    if (!descSetNew.contains(desc)) {
                        descSetNew.add(desc);
                    } else {
                        for (ResultDesc d : descSetNew) {
                            if (d.compareTo(desc) == 0) {
                                d.getTestResultUidList().addAll(desc.getTestResultUidList());
                            }
                        }
                    }
                }

                for (ResultDesc desc : descSetNew) {
                    if (desc.getValue() != null) {
                        resultDescArray.put(desc.toJson());
                    }
                }

            }
            //System.out.println(resultDescArray);
            //put result descriptions to json
            answer.put("testresultdetail_desc", resultDescArray);

            QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale);
            JSONArray testTypeDescArray = new JSONArray();
            for (QoSTestTypeDesc desc : testTypeDao.getAll()) {
                final JSONObject testTypeDesc = desc.toJson();
                if (testTypeDesc != null) {
                    testTypeDescArray.put(testTypeDesc);
                }
            }

            //put result descriptions to json
            answer.put("testresultdetail_testdesc", testTypeDescArray);
            JSONObject evalTimes = new JSONObject();
            evalTimes.put("eval", (timeStampEvalEnd - timeStampEval));
            evalTimes.put("full", (System.currentTimeMillis() - timeStampFullEval));
            answer.put("eval_times", evalTimes);

            //System.out.println(answer);
        } else
            errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID");

    } else
        errorList.addError("ERROR_DB_CONNECTION");
}

From source file:name.wildswift.android.libs.server.json.JsonDomRequest.java

/**
 * Callback to work with response. Called when input from server gets, and return result of request.<br/>
 * Load all server data. Parse JSON and call one of convert methods.
 * Don't override. If need, use {@link  name.wildswift.android.libs.server.ServerRequest} instead
 *
 * @param content input from server side
 * @return result of processing request (data object or other information)
 * @throws name.wildswift.android.libs.exceptions.ServerApiException
 *                             if error in server format of data
 * @throws java.io.IOException if IOErrors occurred
 *//*  w w w .j a  va2 s .  c o  m*/
@Override
public final T processRequest(InputStream content) throws ServerApiException, IOException {
    ByteArrayOutputStream dataCache = new ByteArrayOutputStream();

    // Fully read data
    byte[] buff = new byte[1024];
    int len;
    while ((len = content.read(buff)) >= 0) {
        dataCache.write(buff, 0, len);
    }

    // Close streams
    dataCache.close();

    String jsonString = new String(dataCache.toByteArray()).trim();

    // Check for array index out of bounds
    if (jsonString.length() > 0) {
        try {
            // switch type of Json root object
            if (jsonString.startsWith("{")) {
                return convertJson(new JSONObject(jsonString));
            } else {
                return convertJson(new JSONArray(jsonString));
            }
        } catch (JSONException e) {
            // Box exception
            throw new ServerApiException(e);
        }
    }
    throw new ServerApiException("No data returned");
}

From source file:com.example.android.popularmoviesist2.data.FetchTrailerMovieTask.java

private String[] getMoviesDataFromJson(String moviesJsonStr) throws JSONException {

    final String JSON_LIST = "results";
    final String JSON_ID = "id";
    final String JSON_KEY = "key";
    final String JSON_NAME = "name";
    final String JSON_SITE = "site";

    urlYoutbe.clear();/*from   ww w  .  j a  v a2 s .c  om*/

    try {
        JSONObject moviesJson = new JSONObject(moviesJsonStr);
        JSONArray moviesArray = moviesJson.getJSONArray(JSON_LIST);

        final String[] result = new String[moviesArray.length()];

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

            JSONObject movie = moviesArray.getJSONObject(i);
            String id = movie.getString(JSON_ID);
            String key = movie.getString(JSON_KEY);
            String name = movie.getString(JSON_NAME);
            String site = movie.getString(JSON_SITE);

            result[i] = key;
        }
        return result;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }

}

From source file:com.hueemulator.lighting.utils.TestUtils.java

/**
 * Tests two JSON strings for equality by performing a deep comparison.
 *
 * @param json1 represents a JSON object to compare with json2
 * @param json2 represents a JSON object to compare with json1
 * @return true if the JSON objects are equal, false otherwise
 *///from   www  .ja v  a  2  s.com
public static boolean jsonsEqual(String json1, String json2) throws Exception {
    Object obj1Converted = convertJsonElement(new JSONObject(json1));
    Object obj2Converted = convertJsonElement(new JSONObject(json2));
    return obj1Converted.equals(obj2Converted);
}

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

public void readData() throws JSONException {
    MYLOG("readData() start");

    if (SFparkActivity.responseString == null || SFparkActivity.responseString == "") {
        return;/*ww w . j a  va2s .  c o  m*/
    }

    String message = null;
    JSONObject rootObject = null;
    JSONArray jsonAVL = null;

    rootObject = new JSONObject(SFparkActivity.responseString);
    message = rootObject.getString("MESSAGE");
    jsonAVL = rootObject.getJSONArray("AVL");
    timeStampXML = rootObject.getString("AVAILABILITY_UPDATED_TIMESTAMP");

    MYLOG(message);

    int i = 0;
    int len = jsonAVL.length();

    if (annotations == null) {
        annotations = new ArrayList<MyAnnotation>();
    } else {
        annotations.clear();
    }

    for (i = 0; i < len; ++i) {
        JSONObject interestArea = jsonAVL.getJSONObject(i);
        MyAnnotation annotation = new MyAnnotation();
        annotation.allGarageData = interestArea;
        annotation.initFromData();

        // new: UBER-HACK! SFMTA wants me to hide the Calif/Steiner lot.
        if ("California and Steiner Lot".equals(annotation.title))
            continue;

        annotations.add(annotation);
    }

    MYLOG("readData() finish ");
}