Example usage for org.json JSONTokener JSONTokener

List of usage examples for org.json JSONTokener JSONTokener

Introduction

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

Prototype

public JSONTokener(String s) 

Source Link

Document

Construct a JSONTokener from a string.

Usage

From source file:com.voidsearch.data.provider.facebook.SimpleGraphAPIClient.java

/**
 * get response from Graph API//from  w ww  .  ja  v a 2 s.co  m
 *
 * @param query
 * @return
 * @throws Exception
 */
private JSONObject getResponse(String query) throws Exception {
    if (!(query.contains("?") && query.contains(ACCESS_TOKEN_PARAM))) {
        query += "?" + ACCESS_TOKEN_PARAM + "=" + URLEncoder.encode(accessToken);
    }

    // force query delay interval
    long lastQueryElapsed = getQueryDelay();
    if (lastQueryElapsed < queryDelay) {
        Thread.sleep(queryDelay - lastQueryElapsed);
    }
    resetQueryTimer();

    byte[] response = get(query);
    return new JSONObject(new JSONTokener(new StringReader(new String(new String(response)))));
}

From source file:com.watabou.pixeldungeon.utils.Bundle.java

public static Bundle read(InputStream stream) {

    try {/* w w  w . j ava  2 s . co m*/
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        JSONObject json = (JSONObject) new JSONTokener(reader.readLine()).nextValue();
        reader.close();

        return new Bundle(json);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.watabou.pixeldungeon.utils.Bundle.java

public static Bundle read(byte[] bytes) {
    try {/*from   ww w.j av  a  2s.  c  o m*/

        JSONObject json = (JSONObject) new JSONTokener(new String(bytes)).nextValue();
        return new Bundle(json);

    } catch (JSONException e) {
        return null;
    }
}

From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java

public ICalTask(ActionManager actionManager, String providerId, VEvent event, TaskExecutionListener listener)
        throws InvalidVEventException {
    this.actionManager = actionManager;
    this.providerId = providerId;
    this.event = event;
    this.listener = listener;

    if (event != null) {
        // adjust start time if sun offset is set
        Property sunOffset = event.getProperty(PROP_SUN_OFFSET);
        if (sunOffset != null) {
            try {
                solarOffset = new SolarOffset(sunOffset.getValue());
            } catch (ParseException e) {
                throw new InvalidVEventException("Invalid X-SUN-OFFSET", e);
            }/*from   w ww.  j av a 2  s . co m*/
        }

        // parse actions
        Property commentProp = event.getProperty("COMMENT");
        if (commentProp != null) {
            JSONArray arr = new JSONArray(new JSONTokener(commentProp.getValue()));
            for (int i = 0; i < arr.length(); i++) {
                JSONObject json = arr.getJSONObject(i);
                if (json.has("pluginId") && json.has("actionId")) {
                    addActionRef(json);
                } else {
                    throw new InvalidVEventException("Found scheduled event with no plugin and/or action");
                }
            }
        } else {
            throw new InvalidVEventException("ICalEventTask event must have a COMMENT property");
        }
    } else {
        throw new InvalidVEventException("ICalEventTask must have a non-null event");
    }
}

From source file:org.everit.json.schema.IssueTest.java

private Schema loadSchema() {
    Optional<File> schemaFile = fileByName("schema.json");
    try {//from  w w w.  j  a  va  2s . c om
        if (schemaFile.isPresent()) {
            JSONObject schemaObj = new JSONObject(new JSONTokener(new FileInputStream(schemaFile.get())));
            return SchemaLoader.load(schemaObj);
        }
        throw new RuntimeException(issueDir.getCanonicalPath() + "/schema.json is not found");
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.everit.json.schema.IssueTest.java

private Object loadJsonFile(final File file) {

    Object subject = null;//w w w .j  av a2  s . co m

    try {
        JSONTokener jsonTok = new JSONTokener(new FileInputStream(file));

        // Determine if we have a single JSON object or an array of them
        Object jsonTest = jsonTok.nextValue();
        if (jsonTest instanceof JSONObject) {
            // The message contains a single JSON object
            subject = jsonTest;
        } else if (jsonTest instanceof JSONArray) {
            // The message contains a JSON array
            subject = jsonTest;
        }
    } catch (JSONException e) {
        throw new RuntimeException("failed to parse subject json file", e);
    } catch (FileNotFoundException e) {
        throw new UncheckedIOException(e);
    }
    return subject;
}

From source file:com.android.i18n.addressinput.FormatInterpreter.java

private static String getJsonValue(String regionCode, AddressDataKey key) {
    Util.checkNotNull(regionCode);
    String jsonString = RegionDataConstants.getCountryFormatMap().get(regionCode);
    Util.checkNotNull(jsonString, "no json data for region code " + regionCode);

    try {/*from  w  ww.  ja v  a  2s .co  m*/
        JSONObject jsonObj = new JSONObject(new JSONTokener(jsonString));
        if (!jsonObj.has(key.name().toLowerCase())) {
            // Key not found. Return null.
            return null;
        }
        // Gets the string for this key.
        String parsedJsonString = jsonObj.getString(key.name().toLowerCase());
        return parsedJsonString;
    } catch (JSONException e) {
        throw new RuntimeException("Invalid json for region code " + regionCode + ": " + jsonString);
    }
}

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

public BayeuxMessage(String jsonMessage) throws JSONException {
    JSONTokener jsont = new JSONTokener(jsonMessage);
    JSONArray jsona = new JSONArray(jsont);
    // FIXME ? msg   .
    JSONObject jsono = jsona.getJSONObject(0);
    // channel //from w w w.j a  va2s .  c o m
    channel = jsono.getString("channel");
    if (channel != null && channel.startsWith("/meta/")) {
        if ("/meta/handshake".equals(channel)) {
            // type 
            type = BayeuxMessage.HANDSHAKE_REQ;
            // version 
            version = jsono.getString("version");
            JSONArray jsonaSupportedConnectionTypes = jsono.getJSONArray("supportedConnectionTypes");
            supportedConnectionTypesList = new ArrayList<String>();
            // supportedConnectionTypes 
            for (int i = 0; i < jsonaSupportedConnectionTypes.length(); i++) {
                supportedConnectionTypesList.add(jsonaSupportedConnectionTypes.getString(i));
            }
            // Handshake req ?  mandatory ? ? ?.
        } else if ("/meta/connect".equals(channel)) {
            type = BayeuxMessage.CONNECT_REQ;
            clientId = jsono.getString("clientId");
            connectionType = jsono.getString("connectionType");
        } else if ("/meta/disconnect".equals(channel)) {
            type = BayeuxMessage.DISCONNECT_REQ;
            clientId = jsono.getString("clientId");
        } else if ("/meta/subscribe".equals(channel)) {
            type = BayeuxMessage.SUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        } else if ("/meta/unsubscribe".equals(channel)) {
            type = BayeuxMessage.UNSUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        }
    } else {
        type = BayeuxMessage.PUBLISH_REQ;
        data = jsono.getString("data");
    }
}

From source file:com.pansapiens.occyd.JSONdecoder.java

/**
* Abstract utility class for parsing JSON objects (as strings) and
* returning Java objects./*from ww  w  .j  a  v  a 2 s .  c  o  m*/
*/
public static ArrayList<Post> json2postArray(String json_txt) throws JSONException {
    /**
     * Takes an appropriate JSON format string, returned as a response
     * by the server to a search query, returns an ArrayList
     *  of Post objects. 
     */
    ArrayList<Post> post_results = new ArrayList();

    if (json_txt != null) {
        // http://code.google.com/android/reference/org/json/JSONObject.html
        JSONTokener jsontok = new JSONTokener(json_txt);
        JSONObject json;
        String geohash = null;
        String[] tags = null;

        // TODO: read these from the JSON too
        //String key = null;
        //String user = null;
        //String desc = null;
        //URL link = null;
        // see: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html
        //Date date = null;
        // parse "2008-12-31 03:22:23.350798" format date with:
        // (could have an issue with to many millisecond places SSSSSS .... may need to truncate)
        // SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        // Date date = dateformat.parse(dateString);

        float lat, lon;

        json = new JSONObject(jsontok);

        // catch any error codes in the returned json
        String result = json.getString("result");
        if (!result.equals("done")) {
            return post_results;
        }

        // unpack the json into Post objects, add them to the result list
        JSONArray posts = json.getJSONArray("posts");
        for (int i = 0; i < posts.length(); i++) {
            JSONObject p = posts.getJSONObject(i);
            geohash = (String) p.get("geohash");
            JSONArray coordinates = p.getJSONArray("coordinates");
            lat = (float) coordinates.getDouble(0);
            lon = (float) coordinates.getDouble(1);

            JSONArray t = p.getJSONArray("tags");
            tags = new String[t.length()];
            for (int j = 0; j < t.length(); j++) {
                tags[j] = t.getString(j);
            }

            Post post = new Post(lat, lon, geohash, tags);
            post_results.add(post);
        }
    }
    return post_results;
}

From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java

/**
 * Main method to decode a GeoJSON String
 * //from w w w .  j  a  va2s  .  c o m
 * @param s
 *            The string in GeoJSON format
 * @return if the paramater has inside a FeatureCollection tag, the method
 *         will the decode the GeoJSON String and it will return a
 *         FeatureCollection otherwise, it will return null;
 * @throws JSONException
 */
public FeatureCollection decode(String s) throws JSONException {
    JSONTokener tokener = new JSONTokener(s);

    JSONObject o = new JSONObject(tokener);
    if (o.get("type").equals("FeatureCollection")) {
        return this.decodeFeatureCollection(o);
    } else {
        // TODO
        // throw exception
        return null;
    }

}