Example usage for org.json JSONTokener nextValue

List of usage examples for org.json JSONTokener nextValue

Introduction

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

Prototype

public Object nextValue() throws JSONException 

Source Link

Document

Get the next value.

Usage

From source file:com.jskaleel.xml.JSONObject.java

/**
 * Construct a JSONObject from a JSONTokener.
 *
 * @param x/*  w w  w.  java  2  s .c om*/
 *            A JSONTokener object containing the source string.
 * @throws JSONException
 *             If there is a syntax error in the source string or a
 *             duplicated key.
 * @throws org.json.JSONException 
 */
public JSONObject(JSONTokener x) throws JSONException, org.json.JSONException {
    this();
    char c;
    String key;

    if (x.nextClean() != '{') {
        throw x.syntaxError("A JSONObject text must begin with '{'");
    }
    for (;;) {
        c = x.nextClean();
        switch (c) {
        case 0:
            throw x.syntaxError("A JSONObject text must end with '}'");
        case '}':
            return;
        default:
            x.back();
            key = x.nextValue().toString();
        }

        // The key is followed by ':'.

        c = x.nextClean();
        if (c != ':') {
            throw x.syntaxError("Expected a ':' after a key");
        }
        this.putOnce(key, x.nextValue());

        // Pairs are separated by ','.

        switch (x.nextClean()) {
        case ';':
        case ',':
            if (x.nextClean() == '}') {
                return;
            }
            x.back();
            break;
        case '}':
            return;
        default:
            throw x.syntaxError("Expected a ',' or '}'");
        }
    }
}

From source file:com.example.trafficvolation_android.VolationWebView.java

private void handleJson() {
    String json = "{\"code\":\"0\", \"message\":\"?\", \"result\":[{\"url\":\"http://www.shjtaq.com/zwfg/dzjc_new.asp\"}]}";

    try {/* w  w  w .j ava  2s.c o  m*/
        JSONTokener jsonParser = new JSONTokener(json);

        JSONObject jsonObject = (JSONObject) jsonParser.nextValue();

        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject url = result.getJSONObject(0);
        String resultUrl = url.getString("url");

        Log.d("1", resultUrl + " json");

    } catch (JSONException ex) {
        Log.d("1", "handle json failed");
    }

}

From source file:com.novemser.voicetest.utils.JsonParser.java

public static ArrayList<NewsResult> parseNewsInfo(String json) {
    ArrayList<NewsResult> results = new ArrayList<>();
    try {//  ww  w.ja v  a 2 s  .co  m
        JSONTokener tokener = new JSONTokener(json);
        JSONArray array = (JSONArray) tokener.nextValue();
        int len = array.length();
        for (int i = 0; i < len; i++) {
            JSONObject object = array.getJSONObject(i);

            results.add(new NewsResult(object.getString("url"), object.getString("title"),
                    object.getString("time")));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return results;
}

From source file:com.google.android.apps.muzei.util.IOUtil.java

public static JSONObject readJsonObject(String json) throws IOException, JSONException {
    JSONTokener tokener = new JSONTokener(json);
    Object val = tokener.nextValue();
    if (!(val instanceof JSONObject)) {
        throw new JSONException("Expected JSON object.");
    }/*from   w w  w .  j a  va2 s.  com*/
    return (JSONObject) val;
}

From source file:net.dahanne.gallery3.client.business.G3Client.java

private Item getItems(int albumId, List<Item> items, String type) throws G3GalleryException {
    logger.debug("getting items in albumId : {}, type : {}", albumId, type);
    Item item = this.getItem(albumId);
    Collection<String> members = item.getMembers();
    JSONArray urls = new JSONArray(members);
    try {// ww w  .  jav  a2 s .co m
        String encodedUrls;
        encodedUrls = URLEncoder.encode(urls.toString(), "UTF-8");
        StringBuilder requestToAppend = new StringBuilder();
        requestToAppend.append(INDEX_PHP_REST_ITEMS);
        requestToAppend.append("?urls=");
        requestToAppend.append(encodedUrls);
        requestToAppend.append("&type=");
        requestToAppend.append(type);
        String sendHttpRequest = sendHttpRequest(requestToAppend.toString(), new ArrayList<NameValuePair>(),
                GET, null);

        JSONTokener jsonTokener = new JSONTokener(sendHttpRequest);
        JSONArray jsonResult = (JSONArray) jsonTokener.nextValue();
        for (int i = 0; i < jsonResult.length(); i++) {
            items.add(ItemUtils.parseJSONToItem((JSONObject) jsonResult.get(i)));
        }
    } catch (UnsupportedEncodingException e) {
        throw new G3GalleryException(e);
    } catch (JSONException e) {
        throw new G3GalleryException(e);
    }
    return item;
}

From source file:m2.android.archetype.example.FacebookSdk.internal.Utility.java

public static Object getStringPropertyAsJSON(JSONObject jsonObject, String key, String nonJSONPropertyKey)
        throws JSONException {
    Object value = jsonObject.opt(key);
    if (value != null && value instanceof String) {
        JSONTokener tokener = new JSONTokener((String) value);
        value = tokener.nextValue();
    }//from  w ww .ja  v a  2 s  .  c  o m

    if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) {
        if (nonJSONPropertyKey != null) {
            // Facebook sometimes gives us back a non-JSON value such as
            // literal "true" or "false" as a result.
            // If we got something like that, we present it to the caller as
            // a GraphObject with a single
            // property. We only do this if the caller wants that behavior.
            jsonObject = new JSONObject();
            jsonObject.putOpt(nonJSONPropertyKey, value);
            return jsonObject;
        } else {
            throw new FacebookException("Got an unexpected non-JSON object.");
        }
    }

    return value;

}

From source file:com.auth0.api.internal.ApplicationInfoRequest.java

@Override
public void onResponse(Response response) throws IOException {
    if (!response.isSuccessful()) {
        String message = "Received app info failed response with code " + response.code() + " and body "
                + response.body().string();
        postOnFailure(new IOException(message));
        return;// ww  w . ja v  a 2 s .c  o m
    }
    try {
        String json = response.body().string();
        JSONTokener tokenizer = new JSONTokener(json);
        tokenizer.skipPast("Auth0.setClient(");
        if (!tokenizer.more()) {
            postOnFailure(tokenizer.syntaxError("Invalid App Info JSONP"));
            return;
        }
        Object nextValue = tokenizer.nextValue();
        if (!(nextValue instanceof JSONObject)) {
            tokenizer.back();
            postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info"));
        }
        JSONObject jsonObject = (JSONObject) nextValue;
        Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject);
        Application app = getReader().readValue(jsonObject.toString());
        postOnSuccess(app);
    } catch (JSONException | IOException e) {
        postOnFailure(new APIClientException("Failed to parse JSONP", e));
    }
}

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

static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection,
        RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
    JSONTokener tokener = new JSONTokener(responseString);
    Object resultObject = tokener.nextValue();

    List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
    Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n  Id: %s\n  Size: %d\n  Responses:\n%s\n",
            requests.getId(), responseString.length(), responses);

    return responses;
}

From source file:org.artags.android.app.stackwidget.service.TagService.java

public static List<Tag> getTagList(String url) {
    long start = new Date().getTime();
    Log.i(Constants.LOG_TAG, "Tag Service : begin tag fetching");
    List<Tag> list = new ArrayList<Tag>();
    String jsonflow = HttpUtils.getUrl(url);

    try {/*from   www.  j  av a2s  .  co  m*/

        JSONTokener tokener = new JSONTokener(jsonflow);
        JSONObject json = (JSONObject) tokener.nextValue();
        JSONArray jsonTags = json.getJSONArray("tags");

        int max = (jsonTags.length() < Constants.MAX_TAGS) ? jsonTags.length() : Constants.MAX_TAGS;
        for (int i = 0; i < max; i++) {
            JSONObject jsonTag = jsonTags.getJSONObject(i);
            Tag tag = new Tag();
            tag.setId(jsonTag.getString("id"));
            tag.setText(jsonTag.getString("title"));
            tag.setThumbnailUrl(jsonTag.getString("imageUrl"));
            tag.setRating(jsonTag.getString("rating"));
            list.add(tag);
        }
    } catch (JSONException e) {
        Log.e(Constants.LOG_TAG, "JSON Parsing Error : " + e.getMessage(), e);
    }
    long end = new Date().getTime();
    Log.i(Constants.LOG_TAG, "Tag Service : " + list.size() + " tags fetched in " + (start - end) + "ms");
    return list;
}

From source file:org.araqne.docxcod.test.DocxTest.java

@Test
public void totalTest() throws IOException, JSONException {
    File targetDir = new File(".test/_totalTest");
    File saveFile = new File(".test/totalTest-save.docx");
    saveFile.delete();/* w w w.ja  va  2s .c o  m*/
    targetDir.mkdirs();
    // tearDownHelper.add(targetDir);

    OOXMLPackage docx = new OOXMLPackage();
    docx.load(getClass().getResourceAsStream("/totalTest.docx"), targetDir);
    docx.setOutputStream(new FileOutputStream(saveFile));

    InputStreamReader inputReader = new InputStreamReader(getClass().getResourceAsStream("/totalTest.in"),
            Charset.forName("utf-8"));
    JSONTokener tokener = new JSONTokener(inputReader);
    Map<String, Object> rootMap = JsonHelper.parse((JSONObject) tokener.nextValue());

    docx.apply(new MergeFieldParser(), rootMap);
    docx.apply(new DirectivePlacerProcessor(), rootMap);
    docx.apply(new ChartDirectiveParser(), rootMap);
    docx.apply(new MagicNodeUnwrapper("word/document.xml"), rootMap);
    docx.apply(new FreeMarkerRunner("word/document.xml"), rootMap);

    docx.setDebug(true);
    docx.close();
    // tearDownHelper.add(saveFile);
}