List of usage examples for org.json JSONTokener JSONTokener
public JSONTokener(String s)
From source file:ai.susi.mind.SusiInference.java
/** * The inference must be applicable to thought arguments. This method executes the inference process on an existing * argument and produces another thought which may or may not be appended to the given argument to create a full * argument proof. Within this method also data from the argument is unified with the inference variables * @param flow/*ww w .j a v a 2 s. c o m*/ * @return a new thought as result of the inference */ public SusiThought applyProcedures(SusiArgument flow) { Type type = this.getType(); if (type == SusiInference.Type.console) { String expression = this.getExpression(); if (expression.length() == 0) { // this might have an anonymous console rule inside JSONObject definition = this.getDefinition(); if (definition == null) return new SusiThought(); // execute the console rule right here SusiThought json = new SusiThought(); try { String url = flow.unify(definition.getString("url")); String path = flow.unify(definition.getString("path")); JSONTokener serviceResponse = new JSONTokener( new ByteArrayInputStream(ConsoleService.loadData(url))); JSONArray data = JsonPath.parse(serviceResponse, path); if (data != null) json.setData(new SusiTransfer("*").conclude(data)); json.setHits(json.getCount()); } catch (Throwable e) { //e.printStackTrace(); // probably a time-out } return json; } else { try { return ConsoleService.dbAccess.deduce(flow, flow.unify(expression)); } catch (Exception e) { } } } if (type == SusiInference.Type.flow) { String expression = flow.unify(this.getExpression()); try { return flowProcedures.deduce(flow, expression); } catch (Exception e) { } } if (type == SusiInference.Type.memory) { String expression = flow.unify(this.getExpression()); try { return memoryProcedures.deduce(flow, expression); } catch (Exception e) { } } if (type == SusiInference.Type.javascript) { String expression = flow.unify(this.getExpression()); try { return javascriptProcedures.deduce(flow, expression); } catch (Exception e) { } } if (type == SusiInference.Type.prolog) { String expression = flow.unify(this.getExpression()); try { return prologProcedures.deduce(flow, expression); } catch (Exception e) { } } // maybe the argument is not applicable, then an empty thought is produced (which means a 'fail') return new SusiThought(); }
From source file:com.gistlabs.mechanize.document.json.JsonTest.java
/** * Example from https://www.dropbox.com/developers/reference/api#account-info in dropbox.account.info.json *///from w ww. j a v a 2 s . c o m @Test public void testJsonParsing() throws Exception { JSONObject json = new JSONObject(new JSONTokener( new InputStreamReader(getClass().getResourceAsStream("impl/dropbox.account.info.json")))); assertNotNull(json); assertEquals(12345678, json.getLong("uid")); }
From source file:com.bt.heliniumstudentapp.UpdateClass.java
@Override protected void onPostExecute(String html) { if (html != null) { try {/*from w w w . j ava 2 s . co m*/ final JSONObject json = (JSONObject) new JSONTokener(html).nextValue(); versionName = json.optString("version_name"); final int versionCode = json.optInt("version_code"); try { final int currentVersionCode = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0).versionCode; if (versionCode > currentVersionCode) { if (!settings) updateDialog.show(); updateDialog.setTitle(context.getString(R.string.update) + ' ' + versionName); final TextView contentTV = (TextView) updateDialog.findViewById(R.id.tv_content_du); contentTV.setTextColor(ContextCompat.getColor(context, MainActivity.themePrimaryTextColor)); contentTV.setText(Html.fromHtml(json.optString("content"), null, new Html.TagHandler() { @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { if ("li".equals(tag)) if (opening) output.append(" \u2022 "); else output.append("\n"); } })); updateDialog.setCanceledOnTouchOutside(true); updateDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true); updateDialog.getButton(AlertDialog.BUTTON_POSITIVE) .setTextColor(ContextCompat.getColor(context, MainActivity.accentSecondaryColor)); } else if (settings) { updateDialog.setTitle(context.getString(R.string.update_no)); final TextView contentTV = (TextView) updateDialog.findViewById(R.id.tv_content_du); contentTV.setTextColor(ContextCompat.getColor(context, MainActivity.themePrimaryTextColor)); contentTV.setText(Html.fromHtml(json.optString("content"), null, new Html.TagHandler() { @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { if ("li".equals(tag)) if (opening) output.append(" \u2022 "); else output.append("\n"); } })); updateDialog.setCanceledOnTouchOutside(true); } } catch (NameNotFoundException e) { Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show(); } } else if (settings) { updateDialog.cancel(); final AlertDialog.Builder updateDialogBuilder = new AlertDialog.Builder( new ContextThemeWrapper(context, MainActivity.themeDialog)); updateDialogBuilder.setTitle(context.getString(R.string.update)); updateDialogBuilder.setMessage(R.string.error_update); updateDialogBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { downloadAPK(); } }); updateDialogBuilder.setNegativeButton(android.R.string.no, null); final AlertDialog updateDialog = updateDialogBuilder.create(); updateDialog.setCanceledOnTouchOutside(true); updateDialog.show(); updateDialog.getButton(AlertDialog.BUTTON_POSITIVE) .setTextColor(ContextCompat.getColor(context, MainActivity.accentSecondaryColor)); updateDialog.getButton(AlertDialog.BUTTON_NEGATIVE) .setTextColor(ContextCompat.getColor(context, MainActivity.accentSecondaryColor)); } }
From source file:com.github.michalbednarski.intentslab.browser.FetcherManager.java
static Fetcher unserializeFetcher(String serialized) { JSONTokener tokenizer = new JSONTokener(serialized); try {//from w w w . ja v a 2 s. co m JSONObject jsonObject = (JSONObject) tokenizer.nextValue(); String type = jsonObject.getString("_type"); for (Fetcher.Descriptor descriptor : FETCHER_REGISTRY) { if (descriptor.internalName.equals(type)) { return descriptor.unserializeFromJSON(jsonObject); } } } catch (JSONException e) { throw new RuntimeException(e); } throw new RuntimeException("Unknown _type"); }
From source file:ded.model.Diagram.java
/** Read Diagram JSON out of 'r'. */ public static Diagram readFromReader(Reader r) throws Exception { // Parse the raw characters into a JSON tree. JSONObject obj = new JSONObject(new JSONTokener(r)); // Parse the JSON tree into a Diagram object graph. return new Diagram(obj); }
From source file:ded.model.Diagram.java
/** Deserialize a JSON string; may throw JSONException. */ public static Diagram parseJSONString(String json) throws JSONException { return new Diagram(new JSONObject(new JSONTokener(new StringReader(json)))); }
From source file:com.tianxia.lib.baseworld.sync.http.JsonHttpResponseHandler.java
protected Object parseResponse(String responseBody) throws JSONException { return new JSONTokener(responseBody).nextValue(); }
From source file:nz.co.wholemeal.christchurchmetro.FavouritesActivity.java
private void initFavourites() { SharedPreferences favourites = getSharedPreferences(PlatformActivity.PREFERENCES_FILE, 0); String stops_json = favourites.getString("favouriteStops", null); if (stops_json != null) { Log.d(TAG, "initFavourites(): stops_json = " + stops_json); try {//from w ww . j a v a2s . c o m ArrayList favouriteStops = new ArrayList<Stop>(); JSONArray stopsArray = (JSONArray) new JSONTokener(stops_json).nextValue(); for (int i = 0; i < stopsArray.length(); i++) { try { String platformTag = (String) stopsArray.get(i); Log.d(TAG, "Loading stop platformTag = " + platformTag); Stop stop = new Stop(platformTag, null, getApplicationContext()); favouriteStops.add(stop); Log.d(TAG, "initFavourites(): added stop platformTag = " + stop.platformTag); } catch (Stop.InvalidPlatformNumberException e) { Log.e(TAG, "Invalid platformTag in favourites: " + e.getMessage()); } catch (JSONException e) { Log.e(TAG, "JSONException() parsing favourites: " + e.getMessage()); } } if (favouriteStops.size() > 0) { stops.addAll(favouriteStops); } } catch (JSONException e) { Log.e(TAG, "initFavourites(): JSONException: " + e.toString()); } } }
From source file:com.nolanofra.test.lazyLoader.MainActivity.java
private ArrayList<Video> getVideos(String url) { ArrayList<Video> videos = new ArrayList<Video>(); String jsonString = executeGet(url); JSONTokener tokener = new JSONTokener(jsonString); JSONObject objectMain = null;// w w w. j a v a 2 s .c o m try { objectMain = new JSONObject(tokener); } catch (JSONException e) { e.printStackTrace(); } JSONObject data = null; JSONArray itemsArray = null; try { data = objectMain.getJSONObject("data"); } catch (JSONException e) { e.printStackTrace(); } try { itemsArray = data.getJSONArray("items"); for (int i = 0; i < itemsArray.length(); i++) { JSONObject videoRoot = itemsArray.getJSONObject(i); JSONObject video = videoRoot.getJSONObject("video"); Video v = new Video(); v.title = video.getString("title"); if (!video.isNull("description")) v.description = video.getString("description"); if (!video.isNull("thumbnail")) { JSONObject thumbnail = video.getJSONObject("thumbnail"); v.thumbnailHQDefault = thumbnail.getString("hqDefault"); v.thumbnailSQDefault = thumbnail.getString("sqDefault"); } videos.add(v); } } catch (Exception e) { Log.d("error", e.getMessage()); } return videos; }
From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java
/** * Load book from JSON file./*w ww .j a va 2s .c om*/ * * @return */ public static Book loadBook(File file) throws Exception { Book book = new Book(); if (!file.exists()) { book.setName("Book"); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.set(Calendar.DAY_OF_MONTH, 1); // create period Period newPeriod = new Period(cal.getTime()); newPeriod.setId(Formatter.formatDateId(cal.getTime())); book.getPeriodList().add(newPeriod); book.setCurrPeriod(newPeriod); book.getAssetList().setName(App.getGuiProp("default.assets")); book.getLiabilityList().setName(App.getGuiProp("default.liability")); book.getExpenseList().setName(App.getGuiProp("default.expenses")); book.getIncomeList().setName(App.getGuiProp("default.income")); return book; } FileReader fr = null; try { fr = new FileReader(file); JSONTokener jsonTokener = new JSONTokener(fr); JSONObject root = new JSONObject(jsonTokener); JSONObject jsonBook = root.getJSONObject("book"); book.setName(jsonBook.getString("name")); book.setCurrPeriodId(jsonBook.getString("currPeriodId")); parseAccounts(jsonBook.getJSONObject("assets"), book.getAssetList()); parseAccounts(jsonBook.getJSONObject("liability"), book.getLiabilityList()); parseAccounts(jsonBook.getJSONObject("income"), book.getIncomeList()); parseAccounts(jsonBook.getJSONObject("expenses"), book.getExpenseList()); parsePeriods(jsonBook.getJSONArray("periodList"), book.getPeriodList(), book); } finally { if (fr != null) { fr.close(); } } return book; }