List of usage examples for org.json JSONObject JSONObject
public JSONObject(String source) throws JSONException
From source file:eu.the4thfloor.volleyextended.toolbox.JsonObjectRequest.java
@Override protected Response<JSONObject> parseNetworkResponse(final NetworkResponse response) { try {/*from ww w . j a v a2 s . com*/ final String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (final UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (final JSONException je) { return Response.error(new ParseError(je)); } }
From source file:ai.susi.mind.SusiCognition.java
public SusiCognition(final SusiMind mind, final String query, int timezoneOffset, double latitude, double longitude, int maxcount, ClientIdentity identity) { this.json = new JSONObject(true); // get a response from susis mind String client = identity.getClient(); this.setQuery(query); this.json.put("count", maxcount); SusiThought observation = new SusiThought(); observation.addObservation("timezoneOffset", Integer.toString(timezoneOffset)); if (!Double.isNaN(latitude) && !Double.isNaN(longitude)) { observation.addObservation("latitude", Double.toString(latitude)); observation.addObservation("longitude", Double.toString(longitude)); }//from ww w . j ava 2 s . c o m this.json.put("client_id", Base64.getEncoder().encodeToString(UTF8.getBytes(client))); long query_date = System.currentTimeMillis(); this.json.put("query_date", DateParser.utcFormatter.print(query_date)); // compute the mind reaction List<SusiArgument> dispute = mind.react(query, maxcount, client, observation); long answer_date = System.currentTimeMillis(); // store answer and actions into json this.json.put("answers", new JSONArray( dispute.stream().map(argument -> argument.finding(client, mind)).collect(Collectors.toList()))); this.json.put("answer_date", DateParser.utcFormatter.print(answer_date)); this.json.put("answer_time", answer_date - query_date); this.json.put("language", "en"); }
From source file:org.entrystore.ldcache.LDCache.java
public LDCache(Context parentContext, URI configURI) throws IOException, JSONException { super(parentContext); getContext().getAttributes().put(KEY, this); if (configURI == null) { configURI = getConfigurationURI("ldcache.json"); }//from www. j av a 2 s . c om if (configURI != null && "file".equals(configURI.getScheme())) { config = new JSONObject(new String(Files.readAllBytes(Paths.get(configURI)))); cache = new CacheImpl(config); } else { log.error("No configuration found"); System.exit(1); } }
From source file:org.huahinframework.manager.util.JobUtils.java
/** * @param state/* w w w. j a v a2s .co m*/ * @param conf * @return {@link List} of {@link JSONObject} * @throws IOException * @throws InterruptedException */ public static List<JSONObject> listJob(State state, JobConf conf) throws IOException, InterruptedException { List<JSONObject> l = new ArrayList<JSONObject>(); Cluster cluster = new Cluster(conf); for (JobStatus jobStatus : cluster.getAllJobStatuses()) { jobStatus.getState(); if (state == null || state == jobStatus.getState()) { Map<String, Object> m = getJob(jobStatus); if (m != null) { l.add(new JSONObject(m)); } } } return l; }
From source file:com.example.espn.headlines.Util.java
/** * Parse a server response into a JSON Object. This is a basic * implementation using org.json.JSONObject representation. More * sophisticated applications may wish to do their own parsing. * * The parsed JSON is checked for a variety of error fields and * a FacebookException is thrown if an error condition is set, * populated with the error message and error type or code if * available./*from w w w . j a va 2 s .co m*/ * * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ public static JSONObject parseJson(String response) throws JSONException, FacebookError { // Edge case: when sending a POST request to /[post_id]/likes // the return value is 'true' or 'false'. Unfortunately // these values cause the JSONObject constructor to throw // an exception. if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response = "{value : true}"; } JSONObject json = new JSONObject(response); // errors set by the server are not consistent // they depend on the method and endpoint if (json.has("error")) { JSONObject error = json.getJSONObject("error"); throw new FacebookError(error.getString("message"), error.getString("type"), 0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"), "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; }
From source file:ru.redcraft.pinterest4j.core.api.PinAPI.java
public List<Comment> getComments(Pin pin) { LOG.debug("Getting comments for pin = " + pin); List<Comment> comments = new ArrayList<Comment>(); Document doc = null;/*from w w w .j a v a 2 s . com*/ String axajResponse = null; try { axajResponse = new APIRequestBuilder(pin.getURL()).setErrorMessage(PIN_API_ERROR).build().getResponse() .getEntity(String.class); doc = Jsoup.parse(new JSONObject(axajResponse).getString("footer")); } catch (JSONException e) { throw new PinterestRuntimeException(PIN_API_ERROR + axajResponse, e); } for (Element comment : doc.select("div.comment")) { long id = Long.valueOf(comment.getElementsByClass("DeleteComment").first().attr("data")); Element contentMeta = comment.getElementsByClass("CommenterMeta").first(); User user = new LazyUser(contentMeta.getElementsByTag("a").first().attr("href").replace("/", ""), getApiManager()); contentMeta.getElementsByTag("a").remove(); String text = contentMeta.text(); comments.add(new CommentImpl(id, text, user, pin)); } LOG.debug("Comments extracted: " + comments); return comments; }
From source file:com.dattasmoon.pebble.plugin.FireReceiver.java
public void sendAlertToPebble(final Context context, int bundleVersionCode, String title, String body) { // Create json object to be sent to Pebble final Map<String, Object> data = new HashMap<String, Object>(); data.put("title", title); data.put("body", body); final JSONObject jsonData = new JSONObject(data); final String notificationData = new JSONArray().put(jsonData).toString(); // Create the intent to house the Pebble notification final Intent i = new Intent(Constants.INTENT_SEND_PEBBLE_NOTIFICATION); i.putExtra("messageType", Constants.PEBBLE_MESSAGE_TYPE_ALERT); i.putExtra("sender", context.getString(R.string.app_name)); i.putExtra("notificationData", notificationData); // Send the alert to Pebble if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "About to send a modal alert to Pebble: " + notificationData); }//from ww w .j a v a 2 s . c o m context.sendBroadcast(i); }
From source file:com.mobiperf_library.util.MeasurementJsonConvertor.java
public static JSONObject encodeToJson(Object obj) throws JSONException { String str = gson.toJson(obj); return new JSONObject(str); }
From source file:net.mandaria.radioreddit.apis.RedditAPI.java
public static RedditAccount login(Context context, String username, String password) { RedditAccount account = new RedditAccount(); try {//w ww. j av a2 s. c om String url = context.getString(R.string.reddit_login) + "/" + username; // post values ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>(); BasicNameValuePair user = new BasicNameValuePair("user", username); post_values.add(user); BasicNameValuePair passwd = new BasicNameValuePair("passwd", password); post_values.add(passwd); BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json"); post_values.add(api_type); String outputLogin = HTTPUtil.post(context, url, post_values); JSONTokener reddit_login_tokener = new JSONTokener(outputLogin); JSONObject reddit_login_json = new JSONObject(reddit_login_tokener); JSONObject json = reddit_login_json.getJSONObject("json"); if (json.getJSONArray("errors").length() > 0) { String error = json.getJSONArray("errors").getJSONArray(0).getString(1); account.ErrorMessage = error; } else { JSONObject data = json.getJSONObject("data"); // success! String cookie = data.getString("cookie"); String modhash = data.getString("modhash"); account.Username = username; account.Cookie = cookie; account.Modhash = modhash; account.ErrorMessage = ""; } } catch (Exception ex) { // We fail to get the streams... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); account.ErrorMessage = ex.toString(); } return account; }
From source file:net.mandaria.radioreddit.apis.RedditAPI.java
public static String Vote(Context context, RedditAccount account, int voteDirection, String fullname) { String errorMessage = ""; try {/*w w w .ja va 2 s. co m*/ try { account.Modhash = updateModHash(context); if (account.Modhash == null) { errorMessage = context.getString(R.string.error_ThereWasAProblemVotingPleaseTryAgain); return errorMessage; } } catch (Exception ex) { errorMessage = ex.getMessage(); return errorMessage; } String url = context.getString(R.string.reddit_vote); // post values ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>(); BasicNameValuePair id = new BasicNameValuePair("id", fullname); post_values.add(id); BasicNameValuePair dir = new BasicNameValuePair("dir", Integer.toString(voteDirection)); post_values.add(dir); // not required //BasicNameValuePair r = new BasicNameValuePair("r", "radioreddit"); // TODO: shouldn't be hard coded, could be talkradioreddit //post_values.add(r); BasicNameValuePair uh = new BasicNameValuePair("uh", account.Modhash); post_values.add(uh); BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json"); post_values.add(api_type); String outputVote = HTTPUtil.post(context, url, post_values); JSONTokener reddit_vote_tokener = new JSONTokener(outputVote); JSONObject reddit_vote_json = new JSONObject(reddit_vote_tokener); if (reddit_vote_json.has("json")) { JSONObject json = reddit_vote_json.getJSONObject("json"); if (json.has("errors") && json.getJSONArray("errors").length() > 0) { String error = json.getJSONArray("errors").getJSONArray(0).getString(1); errorMessage = error; } } // success! } catch (Exception ex) { // We fail to vote... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); errorMessage = ex.toString(); } return errorMessage; }