Here are the examples of the java api class org.json.me.JSONObject taken from open source projects.
1. CommentsLoadOperation#parseComments()
Project: pluotsorbet
File: CommentsLoadOperation.java
File: CommentsLoadOperation.java
/** * Parse a JSON data string into a Vector of CommentThing objects. * * @param commentsJson JSON reply to parse into Comments * @param startLevel Level of hierarchy to start at (most of the time 0) */ protected void parseComments(final String commentsJson, final int startLevel) { Vector comments = new Vector(); JSONObject listingJsonObject; try { // Recurse through any replies and their replies and ... listingJsonObject = new JSONArray(commentsJson).getJSONObject(1); recursivelyAddReplies(comments, listingJsonObject, startLevel); } catch (JSONException e) { System.out.println("Error parsing JSON response: " + e.getMessage()); } // Signal the listener when done finished = true; if (!aborted) { listener.commentsReceived(comments); } }
2. XML#toString()
Project: pluotsorbet
File: XML.java
File: XML.java
/** * Convert a JSONObject into a well-formed, element-normal XML string. * @param o A JSONObject. * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException */ public static String toString(Object o, String tagName) throws JSONException { StringBuffer b = new StringBuffer(); int i; JSONArray ja; JSONObject jo; String k; Enumeration keys; int len; String s; Object v; if (o instanceof JSONObject) { if (tagName != null) { b.append('<'); b.append(tagName); b.append('>'); } // Loop thru the keys. jo = (JSONObject) o; keys = jo.keys(); while (keys.hasMoreElements()) { k = keys.nextElement().toString(); v = jo.get(k); if (v instanceof String) { s = (String) v; } else { s = null; } if (k.equals("content")) { if (v instanceof JSONArray) { ja = (JSONArray) v; len = ja.length(); for (i = 0; i < len; i += 1) { if (i > 0) { b.append('\n'); } b.append(escape(ja.get(i).toString())); } } else { b.append(escape(v.toString())); } // Emit an array of similar keys } else if (v instanceof JSONArray) { ja = (JSONArray) v; len = ja.length(); for (i = 0; i < len; i += 1) { b.append(toString(ja.get(i), k)); } } else if (v.equals("")) { b.append('<'); b.append(k); b.append("/>"); // Emit a new tag <k> } else { b.append(toString(v, k)); } } if (tagName != null) { // Emit the </tagname> close tag b.append("</"); b.append(tagName); b.append('>'); } return b.toString(); // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an <array> element. } else if (o instanceof JSONArray) { ja = (JSONArray) o; len = ja.length(); for (i = 0; i < len; ++i) { b.append(toString(ja.opt(i), (tagName == null) ? "array" : tagName)); } return b.toString(); } else { s = (o == null) ? "null" : escape(o.toString()); return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">"; } }
3. XML#toJSONObject()
Project: pluotsorbet
File: XML.java
File: XML.java
/** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code><[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more()) { x.skipPast("<"); parse(x, o, null); } return o; }
4. XML#parse()
Project: pluotsorbet
File: XML.java
File: XML.java
/** * Scan the content following the named tag, attaching it to the context. * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; String n; JSONObject o = null; String s; Object t; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << t = x.nextToken(); if (t == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { t = x.nextToken(); if (t.equals("CDATA")) { if (x.next() == '[') { s = x.nextCDATA(); if (s.length() > 0) { context.accumulate("content", s); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { t = x.nextMeta(); if (t == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (t == LT) { i += 1; } else if (t == GT) { i -= 1; } } while (i > 0); return false; } else if (t == QUEST) { // <? x.skipPast("?>"); return false; } else if (t == SLASH) { if (name == null || !x.nextToken().equals(name)) { throw x.syntaxError("Mismatched close tag"); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (t instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { n = (String) t; t = null; o = new JSONObject(); for (; ; ) { if (t == null) { t = x.nextToken(); } if (t instanceof String) { s = (String) t; t = x.nextToken(); if (t == EQ) { t = x.nextToken(); if (!(t instanceof String)) { throw x.syntaxError("Missing value"); } o.accumulate(s, t); t = null; } else { o.accumulate(s, ""); } // Empty tag <.../> } else if (t == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } context.accumulate(n, o); return false; // Content, between <...> and </...> } else if (t == GT) { for (; ; ) { t = x.nextContent(); if (t == null) { if (name != null) { throw x.syntaxError("Unclosed tag " + name); } return false; } else if (t instanceof String) { s = (String) t; if (s.length() > 0) { o.accumulate("content", s); } // Nested element } else if (t == LT) { if (parse(x, o, n)) { if (o.length() == 0) { context.accumulate(n, ""); } else if (o.length() == 1 && o.opt("content") != null) { context.accumulate(n, o.opt("content")); } else { context.accumulate(n, o); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } }
5. LinksLoadOperation#parseLinks()
Project: pluotsorbet
File: LinksLoadOperation.java
File: LinksLoadOperation.java
/** * Parse a JSON representation of Reddit links into a Vector * of RedditLink objects. * * @param linksJson The JSON response from the server */ private void parseLinks(String linksJson) { JSONObject jsonResponse; JSONArray jsonItems; try { try { jsonResponse = new JSONObject(linksJson); } catch (NumberFormatException nfe) { System.out.println("NFE: " + nfe.getMessage()); return; } jsonItems = jsonResponse.getJSONObject("data").getJSONArray("children"); } catch (JSONException e) { System.out.println("Could not populate from JSON data: " + e.getMessage()); return; } Vector links = new Vector(); int numItems = jsonItems.length(); if (numItems > 0) { LinkThing item; JSONObject jsonObj; for (int i = 0; i < numItems; i++) { try { jsonObj = jsonItems.getJSONObject(i).getJSONObject("data"); item = LinkThing.fromJson(jsonObj); links.addElement(item); } catch (JSONException e) { System.out.println("Could not parse JSON object: " + e.getMessage()); } } } finished = true; linkListener.linksReceived(links); }
6. CommentsLoadOperation#recursivelyAddReplies()
Project: pluotsorbet
File: CommentsLoadOperation.java
File: CommentsLoadOperation.java
/** * Recursively parse the given listingJsonObject for Comments, adding them * into the Vector specified. Will call itself until the comment tree is * whole (until there are no more child JSON objects to parse). * * @param comments Vector of comments * @param listingJsonObject JSON object (comment listing) to parse * @param level Depth level * @throws JSONException In case of a parsing error */ protected void recursivelyAddReplies(Vector comments, JSONObject listingJsonObject, int level) throws JSONException { JSONArray childrenJsonArray = listingJsonObject.getJSONObject("data").getJSONArray("children"); // Reuse the same objects to avoid unnecessary overhead JSONObject thingDataObj; CommentThing comment; for (int i = 0, len = childrenJsonArray.length(); i < len && !aborted; i++) { thingDataObj = childrenJsonArray.getJSONObject(i).getJSONObject("data"); try { // Create a comment item and append it to the list comment = CommentThing.fromJson(thingDataObj); comment.setLevel(level); comments.addElement(comment); } catch (JSONException e) { System.out.println("Could not parse comment JSON: " + e.getMessage()); } // Process any further replies JSONObject repliesJsonObject = thingDataObj.optJSONObject("replies"); if (repliesJsonObject != null) { recursivelyAddReplies(comments, repliesJsonObject, level + 1); } } }