List of usage examples for org.json JSONTokener JSONTokener
public JSONTokener(String s)
From source file:ded.model.SerializationTests.java
public void test1() throws Exception { // Build a simple diagram. Diagram d = new Diagram(); d.windowSize = new Dimension(1000, 2000); Entity e1 = new Entity(); e1.loc = new Point(5, 10); e1.size = new Dimension(30, 40); e1.shape = EntityShape.ES_ELLIPSE;//from w ww .ja va2 s. c om e1.name = "e1"; e1.attributes = "attr1\nattr2\nattr3"; d.entities.add(e1); Entity e2 = new Entity(); e2.loc = new Point(15, 20); e2.size = new Dimension(130, 140); e2.shape = EntityShape.ES_NO_SHAPE; e2.name = "e2"; e2.attributes = "funny\"characters\\in\'this,string!"; d.entities.add(e2); // Relation from e1 to e2 with two control points. Relation r1 = new Relation(new RelationEndpoint(e1), new RelationEndpoint(e2)); r1.controlPts.add(new Point(71, 72)); r1.controlPts.add(new Point(73, 74)); r1.routingAlg = RoutingAlgorithm.RA_DIRECT; r1.label = "r1"; r1.end.arrowStyle = ArrowStyle.AS_FILLED_TRIANGLE; r1.start.arrowStyle = ArrowStyle.AS_DOUBLE_ANGLE; d.relations.add(r1); // Relation between two points. Relation r2 = new Relation(new RelationEndpoint(new Point(81, 82)), new RelationEndpoint(new Point(83, 84))); d.relations.add(r2); // Make e2 inherit from e1. Inheritance i1 = new Inheritance(e1, true /*open*/, new Point(31, 32)); d.inheritances.add(i1); Relation r3 = new Relation(new RelationEndpoint(e2), new RelationEndpoint(i1)); r3.routingAlg = RoutingAlgorithm.RA_MANHATTAN_VERT; d.relations.add(r3); // Make sure it is all consistent. d.selfCheck(); // Serialize it. String serialized = d.toJSON().toString(2); System.out.println(serialized); // Parse it. JSONObject o = new JSONObject(new JSONTokener(serialized)); Diagram d2 = new Diagram(o); d2.selfCheck(); // Check for structural equality. assert (d2.equals(d)); // Serialize and check that for equality too. String ser2 = d2.toJSON().toString(2); assert (ser2.equals(serialized)); }
From source file:ded.model.SerializationTests.java
private static void testParseFile(String fname) throws Exception { System.out.println("testing: " + fname); // Parse the file, checking that we can. Diagram d = Diagram.readFromFileAutodetect(fname); d.selfCheck();//from w ww . j a v a2s. co m // Put it through a serialization cycle. String serialized = d.toJSON().toString(2); Diagram d2 = new Diagram(new JSONObject(new JSONTokener(serialized))); d2.selfCheck(); // The deserialized objects should be equal. assert (d.equals(d2)); // The serialized string form might be different from what was // in the file if we loaded an older version. But if we serialize // again, *that* should match 'serialized'. String ser2 = d2.toJSON().toString(2); assert (serialized.equals(ser2)); }
From source file:org.ttn.android.sdk.api.converter.base.JsonConverter.java
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException { Object obj = null;/*from w w w . j a v a 2 s . co m*/ try { String jsonStr = streamToString(body.in()); Object json = new JSONTokener(jsonStr).nextValue(); if (json instanceof JSONArray) { JSONArray jsonArray = (JSONArray) json; List<Object> coll = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonItem = jsonArray.getJSONObject(i); Object item = fromJson(jsonItem); coll.add(item); } obj = coll; } else if (json instanceof JSONObject) { // no collection. JSONObject jsonObj = (JSONObject) json; obj = fromJson(jsonObj); } } catch (IOException | JSONException e) { throw new ConversionException(e.getMessage()); } return obj; }
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;// w w w. j av a2 s . c om } 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.google.gcloud.datastore.DatastoreServiceException.java
/** * Translate DatastoreException to DatastoreServiceException based on their * HTTP error codes. This method will always throw a new DatastoreServiceException. * * @throws DatastoreServiceException every time *///from www . j av a 2 s.co m static DatastoreServiceException translateAndThrow(DatastoreException exception) { String message = exception.getMessage(); String reason = ""; if (message != null) { try { JSONObject json = new JSONObject(new JSONTokener(message)); JSONObject error = json.getJSONObject("error").getJSONArray("errors").getJSONObject(0); reason = error.getString("reason"); message = error.getString("message"); } catch (JSONException ignore) { // ignore - will be converted to unknown } } Code code = REASON_TO_CODE.get(reason); if (code == null) { code = MoreObjects.firstNonNull(HTTP_TO_CODE.get(exception.getCode()), Code.UNKNOWN); } throw code.translate(exception, message); }
From source file:org.marinemc.util.mojang.MojangUtils.java
public org.json.JSONObject hasJoined(final String username, final String serverHash) throws Throwable { final URLConnection connection = getConnection(getAuthenticationURL(username, serverHash)); final JSONTokener tokener = new JSONTokener(connection.getInputStream()); return new org.json.JSONObject(tokener); }
From source file:test.main1.java
public static void main(String myHelpers[]) throws JSONException, IOException { File f = new File( "C:\\Users\\Bisan Co\\Documents\\NetBeansProjects\\WebApplication1\\src\\java\\test\\newjson.json"); String jsonString = readFile(f.getPath()); jsonOut = new JSONTokener(jsonString); JSONObject output = new JSONObject(jsonOut); ArrayList<user> users = new ArrayList<user>(); String test1 = "user"; for (int i = 1; i < 5; i++) { user test = new user(); String id = (String) output.getJSONObject(test1 + i).get("-ID"); test.setID(id);/* w w w . jav a2 s.c o m*/ String name = (String) output.getJSONObject(test1 + i).get("Name"); test.setName(name); String dop = (String) output.getJSONObject(test1 + i).get("DOB"); test.setDOP(dop); String email = (String) output.getJSONObject(test1 + i).get("Email"); test.setEmail(email); String title = (String) output.getJSONObject(test1 + i).get("Title"); test.setTitle(title); String phone = (String) output.getJSONObject(test1 + i).get("Phone-no."); test.setPhoneNo(phone); JSONArray Friends = (JSONArray) output.getJSONObject(test1 + i).getJSONArray("Friends"); friend test2 = new friend(); location test3 = new location(); for (int j = 0; j < Friends.length(); j++) { String id1 = Friends.getJSONObject(j).getString("-ID"); test2.setID(id1); String name1 = Friends.getJSONObject(j).getString("name"); test2.setName(name1); String loca = Friends.getJSONObject(j).getString("location"); test3.setGPS(loca); String add = Friends.getJSONObject(j).getString("address"); test3.setADD(add); test2.setLocation(test3); test.AddFriend(test2); } users.add(test); } }
From source file:com.cdd.bao.importer.ImportControlledVocab.java
public void exec() throws IOException, JSONException { File f = new File(srcFN); if (!f.exists()) throw new IOException("Source file not found: " + f.getCanonicalPath()); Reader rdr = new FileReader(srcFN); JSONObject json = new JSONObject(new JSONTokener(rdr)); rdr.close();//from w w w. j ava 2 s . c om if (!json.has("columns") || !json.has("rows")) throw new IOException("Source JSON must have 'columns' and 'rows'."); srcColumns = json.getJSONArray("columns"); srcRows = json.getJSONArray("rows"); map = new KeywordMapping(mapFN); Util.writeln("Mapping file:"); Util.writeln(" # identifiers = " + map.identifiers.size()); Util.writeln(" # textblocks = " + map.textBlocks.size()); Util.writeln(" # properties = " + map.properties.size()); Util.writeln(" # values = " + map.values.size()); Util.writeln(" # literals = " + map.literals.size()); Util.writeln(" # references = " + map.references.size()); Util.writeln(" # assertions = " + map.assertions.size()); schema = ModelSchema.deserialise(new File(schemaFN)); assignments = schema.getRoot().flattenedAssignments(); InputStream istr = new FileInputStream(vocabFN); schvoc = SchemaVocab.deserialise(istr, new Schema[] { schema }); istr.close(); for (SchemaVocab.StoredTree stored : schvoc.getTrees()) treeCache.put(stored.assignment, stored.tree); if (hintFN != null) { rdr = new FileReader(hintFN); JSONObject jsonHints = new JSONObject(new JSONTokener(rdr)); rdr.close(); for (String key : jsonHints.keySet()) { String uri = ModelSchema.expandPrefix(jsonHints.getString(key)); hints.put(key, uri); invHints.put(uri, ArrayUtils.add(invHints.get(uri), key)); } Util.writeln(" # hints = " + hints.size()); } checkMappingProperties(); for (int n = 0; n < srcColumns.length(); n++) matchColumn(srcColumns.getString(n)); for (int n = 0; n < srcRows.length(); n++) { Util.writeln("---- Row#" + (n + 1) + " ----"); JSONObject row = srcRows.getJSONObject(n); for (String key : row.keySet()) { if (map.findIdentifier(key) != null) continue; Property prop = map.findProperty(key); if (prop == null || Util.isBlank(prop.propURI)) continue; // passed on the opportunity to map String val = row.optString(key, ""); if (map.findValue(key, val) != null || map.findLiteral(key, val) != null || map.findReference(key, val) != null) continue; // already mapped matchValue(prop, key, val); } } Util.writeln("Saving mapping file..."); map.save(); writeMappedAssays(); Util.writeln("Done."); }
From source file:org.official.json.Cookie.java
/** * Convert a cookie specification string into a JSONObject. The string * will contain a name value pair separated by '='. The name and the value * will be unescaped, possibly converting '+' and '%' sequences. The * cookie properties may follow, separated by ';', also represented as * name=value (except the secure property, which does not have a value). * The name will be stored under the key "name", and the value will be * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into * a JSONObject./* w w w. j ava 2 s .c o m*/ * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other * members. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { String name; JSONObject jo = new JSONObject(); Object value; JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); jo.put("value", x.nextTo(';')); x.next(); while (x.more()) { name = unescape(x.nextTo("=;")); if (x.next() != '=') { if (name.equals("secure")) { value = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); } } else { value = unescape(x.nextTo(';')); x.next(); } jo.put(name, value); } return jo; }
From source file:com.fluidinfo.utils.StringUtil.java
/** * Given a string of json code will return an appropriate representation as a JSONObject * @param jsonInput The string of json code to be turned into a JSONObject instance * @return The resulting JSONObject instance * @throws JSONException If there was a problem processing the jsonInput *//*from w w w . ja v a 2 s . c o m*/ public static JSONObject getJsonObjectFromString(String jsonInput) throws JSONException { JSONTokener jsonResultTokener = new JSONTokener(jsonInput); JSONObject jsonResult = new JSONObject(jsonResultTokener); return jsonResult; }