List of usage examples for org.json JSONTokener JSONTokener
public JSONTokener(String s)
From source file:com.grameenfoundation.ictchallenge.controllers.ConnectedAppREST.java
private JSONObject getFarmerById(String instanceUrl, String accessToken, String id) throws ServletException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); //add key and value httpGet.addHeader("Authorization", "OAuth " + accessToken); try {// w ww. jav a 2 s . com URIBuilder builder = new URIBuilder(instanceUrl + "/services/data/v30.0/query"); //builder.setParameter("q", "SELECT Name, Id from Account LIMIT 100"); builder.setParameter("q", "SELECT Name__c,Date_Of_Birth__c,Land_size__c,Farmer_I_D__c,Picture__c from Farmer__c " + " WHERE Farmer_I_D__c=" + "'" + id + "'"); httpGet.setURI(builder.build()); CloseableHttpResponse closeableresponse = httpclient.execute(httpGet); System.out.println("Response Status line :" + closeableresponse.getStatusLine()); if (closeableresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Now lets use the standard java json classes to work with the // results try { // Do the needful with entity. HttpEntity entity = closeableresponse.getEntity(); InputStream rstream = entity.getContent(); JSONObject authResponse = new JSONObject(new JSONTokener(rstream)); log.log(Level.INFO, "Query response: {0}", authResponse.toString(2)); log.log(Level.INFO, "{0} record(s) returned\n\n", authResponse.getInt("totalSize")); return authResponse; } catch (JSONException e) { e.printStackTrace(); } } } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException ex) { Logger.getLogger(ConnectedAppREST.class.getName()).log(Level.SEVERE, null, ex); } finally { httpclient.close(); } return null; }
From source file:org.qi4j.entitystore.sql.SQLEntityStoreMixin.java
protected DefaultEntityState readEntityState(DefaultEntityStoreUnitOfWork unitOfWork, Reader entityState) throws EntityStoreException { try {/*from w ww . java2s.com*/ ModuleSPI module = unitOfWork.module(); JSONObject jsonObject = new JSONObject(new JSONTokener(entityState)); EntityStatus status = EntityStatus.LOADED; String version = jsonObject.getString("version"); long modified = jsonObject.getLong("modified"); String identity = jsonObject.getString("identity"); // Check if version is correct String currentAppVersion = jsonObject.optString(MapEntityStore.JSONKeys.application_version.name(), "0.0"); if (!currentAppVersion.equals(application.version())) { if (migration != null) { migration.migrate(jsonObject, application.version(), this); } else { // Do nothing - set version to be correct jsonObject.put(MapEntityStore.JSONKeys.application_version.name(), application.version()); } LOGGER.trace("Updated version nr on {} from {} to {}", new Object[] { identity, currentAppVersion, application.version() }); // State changed status = EntityStatus.UPDATED; } String type = jsonObject.getString("type"); EntityDescriptor entityDescriptor = module.entityDescriptor(type); if (entityDescriptor == null) { throw new EntityTypeNotFoundException(type); } Map<QualifiedName, Object> properties = new HashMap<QualifiedName, Object>(); JSONObject props = jsonObject.getJSONObject("properties"); for (PropertyDescriptor propertyDescriptor : entityDescriptor.state().properties()) { Object jsonValue; try { jsonValue = props.get(propertyDescriptor.qualifiedName().name()); } catch (JSONException e) { // Value not found, default it Object initialValue = propertyDescriptor.initialValue(); properties.put(propertyDescriptor.qualifiedName(), initialValue); status = EntityStatus.UPDATED; continue; } if (jsonValue == JSONObject.NULL) { properties.put(propertyDescriptor.qualifiedName(), null); } else { Object value = ((PropertyTypeDescriptor) propertyDescriptor).propertyType().type() .fromJSON(jsonValue, module); properties.put(propertyDescriptor.qualifiedName(), value); } } Map<QualifiedName, EntityReference> associations = new HashMap<QualifiedName, EntityReference>(); JSONObject assocs = jsonObject.getJSONObject("associations"); for (AssociationDescriptor associationType : entityDescriptor.state().associations()) { try { Object jsonValue = assocs.get(associationType.qualifiedName().name()); EntityReference value = jsonValue == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) jsonValue); associations.put(associationType.qualifiedName(), value); } catch (JSONException e) { // Association not found, default it to null associations.put(associationType.qualifiedName(), null); status = EntityStatus.UPDATED; } } Map<QualifiedName, List<EntityReference>> manyAssociations = createManyAssociations(jsonObject, entityDescriptor); Map<QualifiedName, Map<String, EntityReference>> namedAssociations = createNamedAssociations(jsonObject, entityDescriptor); return new DefaultEntityState(unitOfWork, version, modified, EntityReference.parseEntityReference(identity), status, entityDescriptor, properties, associations, manyAssociations, namedAssociations); } catch (JSONException e) { throw new EntityStoreException(e); } }
From source file:org.qi4j.entitystore.sql.SQLEntityStoreMixin.java
public JSONObject getState(String id) throws IOException { Reader reader = getValue(EntityReference.parseEntityReference(id)).getReader(); JSONObject jsonObject;//from w ww . j a v a2s .c o m try { jsonObject = new JSONObject(new JSONTokener(reader)); } catch (JSONException e) { throw new IOException(e); } reader.close(); return jsonObject; }
From source file:menusearch.json.JSONProcessor.java
/** * //w ww . j a va2 s . c o m * @param json formated JSON string containing all the information for one recipe * @return Recipe object * @throws IOException * * This method takes a formated json string containing one recipe, parses it, and saves it into a recipe object which is then returned. * **You must call the getRecipeAPI() method prior to calling this method. */ public static Recipe parseRecipe(String json) throws IOException, JSONException { JSONTokener tokenizer = new JSONTokener(json); JSONObject obj = new JSONObject(tokenizer); Recipe r = new Recipe(); JSONObject attribution = obj.getJSONObject("attribution"); Attribution a = new Attribution(); a.setHTML(attribution.getString("html")); a.setUrl(attribution.getString("url")); a.setText(attribution.getString("text")); a.setLogo(attribution.getString("logo")); r.setAttribution(a); JSONArray ingredientList = obj.getJSONArray("ingredientLines"); for (int i = 0; i < ingredientList.length(); i++) { r.addIngredient(ingredientList.getString(i)); } JSONObject flavors = obj.getJSONObject("flavors"); r.setBitterFlavor(flavors.getDouble("Bitter")); r.setMeatyFlavor(flavors.getDouble("Meaty")); r.setPiquantFlavor(flavors.getDouble("Piquant")); r.setSaltyFlavor(flavors.getDouble("Salty")); r.setSourFlavor(flavors.getDouble("Sour")); r.setSweetFlavor(flavors.getDouble("Sweet")); JSONArray nutritionEstimates = obj.getJSONArray("nutritionEstimates"); for (int i = 0; i < nutritionEstimates.length(); i++) { NutritionEstimate nutritionInfo = new NutritionEstimate(); Unit aUnit = new Unit(); JSONObject nutrition = nutritionEstimates.getJSONObject(i); nutritionInfo.setAttribute(nutrition.getString("attribute")); if (nutrition.isNull("description") != true) nutritionInfo.setDescription(nutrition.getString("description")); nutritionInfo.setValue(nutrition.getDouble("value")); JSONObject unit = nutrition.getJSONObject("unit"); aUnit.setAbbreviation(unit.getString("abbreviation")); aUnit.setName(unit.getString("name")); aUnit.setPlural(unit.getString("plural")); aUnit.setPluralAbbreviation(unit.getString("pluralAbbreviation")); nutritionInfo.addUnit(aUnit); r.addNutritionInfo(nutritionInfo); } JSONArray images = obj.getJSONArray("images"); JSONObject imageBySize = images.getJSONObject(0); for (int i = 0; i < images.length(); i++) { if (images.getJSONObject(i).has("hostedLargeUrl")) r.setHostedlargeUrl(images.getJSONObject(i).getString("hostedLargeUrl")); if (images.getJSONObject(i).has("hostedMediumUrl")) r.setHostedMediumUrl(images.getJSONObject(i).getString("hostedMediumUrl")); if (images.getJSONObject(i).has("hostedSmallUrl")) r.setHostedSmallUrl(images.getJSONObject(i).getString("hostedSmallUrl")); } if (obj.has("name")) r.setName(obj.getString("name")); if (obj.has("yield")) r.setYield(obj.getString("yield")); if (obj.has("totalTime")) r.setTotalTime(obj.getString("totalTime")); if (obj.has("attributes")) { JSONObject attributes = obj.getJSONObject("attributes"); if (attributes.has("holiday")) { JSONArray holidays = attributes.getJSONArray("holiday"); for (int i = 0; i < holidays.length(); i++) { r.addholidayToList(holidays.getString(i)); } } if (attributes.has("cuisine")) { JSONArray cuisine = attributes.getJSONArray("cuisine"); for (int i = 0; i < cuisine.length(); i++) { r.addCuisineToList(cuisine.getString(i)); } } } if (obj.has("totalTimeInSeconds")) r.setTimetoCook(obj.getDouble("totalTimeInSeconds")); if (obj.has("rating")) r.setRating(obj.getDouble("rating")); if (obj.has("numberofServings")) r.setNumberOfServings(obj.getDouble("numberOfServings")); if (obj.has("source")) { JSONObject source = obj.getJSONObject("source"); if (source.has("sourceSiteUrl")) r.setSourceSiteUrl(source.getString("sourceSiteUrl")); if (source.has("sourceRecipeUrl")) r.setSourceRecipeUrl(source.getString("sourceRecipeUrl")); if (source.has("sourceDisplayName")) r.setSourceDisplayName(source.getString("sourceDisplayName")); } r.setRecipeID(obj.getString("id")); return r; }
From source file:menusearch.json.JSONProcessor.java
/** */*from w w w.j ava 2s . c o m*/ * @param JSON string: requires the JSON string of the parameters the user enter for the search * @return RecipeSummaryList: a RecipeSummaryList where it contains information about the recipes that matches the search the user made * @throws java.io.IOException */ public static RecipeSummaryList parseRecipeMatches(String results) throws IOException { CourseList courseList = new CourseList(); RecipeSummaryList list = new RecipeSummaryList(); JSONTokener tokenizer = new JSONTokener(results); JSONObject resultList = new JSONObject(tokenizer); JSONArray matches = resultList.getJSONArray("matches"); for (int i = 0; i < matches.length(); i++) { RecipeSummary r = new RecipeSummary(); JSONObject currentRecipe = matches.getJSONObject(i); JSONObject imageUrls = currentRecipe.getJSONObject("imageUrlsBySize"); String link = "90"; String number = imageUrls.getString(link); r.setImageUrlsBySize(number); String source = (String) currentRecipe.getString("sourceDisplayName"); r.setSourceDisplayName(source); JSONArray listOfIngredients = currentRecipe.getJSONArray("ingredients"); for (int n = 0; n < listOfIngredients.length(); n++) { String currentIngredients = listOfIngredients.getString(n); r.ingredients.add(currentIngredients); } String id = (String) currentRecipe.getString("id"); r.setId(id); String recipe = (String) currentRecipe.get("recipeName"); r.setRecipeName(recipe); JSONArray smallImage = currentRecipe.getJSONArray("smallImageUrls"); for (int l = 0; l < smallImage.length(); l++) { String currentUrl = (String) smallImage.get(l); r.setSmallImageUrls(currentUrl); } int timeInSeconds = (int) currentRecipe.getInt("totalTimeInSeconds"); r.setTotalTimeInSeconds(timeInSeconds); String a = "attributes"; String c = "course"; if (currentRecipe.has(a)) { JSONObject currentAttributes = currentRecipe.getJSONObject(a); if (currentAttributes.has(c)) { for (int j = 0; j < currentAttributes.getJSONArray(c).length(); j++) { String course = currentAttributes.getJSONArray(c).getString(j); courseList.add(course); } r.setCourses(courseList); } } CuisineList cuisineList = new CuisineList(); if (currentRecipe.has(a)) { JSONObject currentAttributes = currentRecipe.getJSONObject(a); if (currentAttributes.has("cuisine")) { for (int j = 0; j < currentAttributes.getJSONArray("cuisine").length(); j++) { String currentCuisine = currentAttributes.getJSONArray("cuisine").getString(j); cuisineList.add(currentCuisine); } r.setCusines(cuisineList); } } String f = "flavors"; JSONObject currentFlavors; if (currentRecipe.has(f) == true) { if (currentRecipe.isNull(f) == false) { currentFlavors = currentRecipe.getJSONObject(f); double saltyRating = currentFlavors.getDouble("salty"); double sourRating = currentFlavors.getDouble("sour"); double sweetRating = currentFlavors.getDouble("sweet"); double bitterRating = currentFlavors.getDouble("bitter"); double meatyRating = currentFlavors.getDouble("meaty"); double piguantRating = currentFlavors.getDouble("piquant"); r.flavors.setSalty(saltyRating); r.flavors.setSour(sourRating); r.flavors.setSweet(sweetRating); r.flavors.setBitter(bitterRating); r.flavors.setMeaty(meatyRating); r.flavors.setPiquant(piguantRating); } if (currentRecipe.get(f) == null) { r.flavors = null; } if (currentRecipe.get(f) == null) r.flavors = null; } double rate = currentRecipe.getInt("rating"); r.setRating(rate); list.matches.add(i, r); } return list; }
From source file:com.github.gorbin.asne.linkedin.LinkedInSocialNetwork.java
private void getAllFriends(String urlString, final ArrayList<SocialPerson> socialPersons, final ArrayList<String> ids, String token) throws Exception { URL url = new URL(urlString); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); checkConnectionErrors(connection);/*from ww w.j ava 2 s . com*/ InputStream inputStream = connection.getInputStream(); String response = streamToString(inputStream); JSONObject jsonObject = (JSONObject) new JSONTokener(response).nextValue(); int jsonStart = 0, jsonCount = 0, jsonTotal = 0; String nextToken = null; if (jsonObject.has("_start")) { jsonStart = jsonObject.getInt("_start"); } if (jsonObject.has("_count")) { jsonCount = jsonObject.getInt("_count"); } if (jsonObject.has("_total")) { jsonTotal = jsonObject.getInt("_total"); } int start = jsonStart + jsonCount; if (jsonTotal > 0 && start > 0 && jsonCount > 0 && jsonTotal > start) { nextToken = LINKEDIN_V1_API + "/people/~/connections" + RequestGetFriendsAsyncTask.fields + "?oauth2_access_token=" + token + FORMAT_JSON + "&start=" + start + "&count=" + RequestGetFriendsAsyncTask.count; } JSONArray jsonResponse = jsonObject.getJSONArray("values"); int length = jsonResponse.length(); for (int i = 0; i < length; i++) { SocialPerson socialPerson = new SocialPerson(); getSocialPerson(socialPerson, jsonResponse.getJSONObject(i)); socialPersons.add(socialPerson); ids.add(jsonResponse.getJSONObject(i).getString("id")); } if ((nextToken != null) && (!TextUtils.isEmpty(nextToken))) { getAllFriends(nextToken, socialPersons, ids, token); } }
From source file:com.github.gorbin.asne.linkedin.LinkedInSocialNetwork.java
private String checkInputStream(HttpURLConnection connection) { String code = null, errorMessage = null; InputStream inputStream = connection.getErrorStream(); String response = streamToString(inputStream); try {// w w w.j av a 2 s . c om JSONObject jsonResponse = (JSONObject) new JSONTokener(response).nextValue(); if (jsonResponse.has("status")) { code = jsonResponse.getString("status"); } if (jsonResponse.has("message")) { errorMessage = jsonResponse.getString("message"); } return "ERROR CODE: " + code + " ERROR MESSAGE: " + errorMessage; } catch (JSONException e) { return e.getMessage(); } }
From source file:curt.android.result.supplement.BookResultInfoRetriever.java
@Override void retrieveSupplementalInfo() throws IOException, InterruptedException { String contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON); if (contents.length() == 0) { return;//ww w . j a v a 2s . c om } String title; String pages; Collection<String> authors = null; try { JSONObject topLevel = (JSONObject) new JSONTokener(contents).nextValue(); JSONArray items = topLevel.optJSONArray("items"); if (items == null || items.isNull(0)) { return; } JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo"); if (volumeInfo == null) { return; } title = volumeInfo.optString("title"); pages = volumeInfo.optString("pageCount"); JSONArray authorsArray = volumeInfo.optJSONArray("authors"); if (authorsArray != null && !authorsArray.isNull(0)) { authors = new ArrayList<String>(); for (int i = 0; i < authorsArray.length(); i++) { authors.add(authorsArray.getString(i)); } } } catch (JSONException e) { throw new IOException(e.toString()); } Collection<String> newTexts = new ArrayList<String>(); if (title != null && title.length() > 0) { newTexts.add(title); } if (authors != null && !authors.isEmpty()) { boolean first = true; StringBuilder authorsText = new StringBuilder(); for (String author : authors) { if (first) { first = false; } else { authorsText.append(", "); } authorsText.append(author); } newTexts.add(authorsText.toString()); } if (pages != null && pages.length() > 0) { newTexts.add(pages + "pp."); } String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context) + "/search?tbm=bks&source=zxing&q="; append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn); }
From source file:org.marietjedroid.connect.MarietjeMessenger.java
/** * Sends a request and handles the response * //from ww w. j ava 2 s . c o m * @param list * @throws MarietjeException */ private void doRequest(List<JSONObject> list) throws MarietjeException { if (list != null) list = new ArrayList<JSONObject>(list); else list = new ArrayList<JSONObject>(); HttpClient httpClient = new DefaultHttpClient(); if (this.token == null) { throw new IllegalStateException("token is null"); } JSONArray json = new JSONArray(); json.put(token); for (JSONObject m : list) json.put(m); HttpGet hp = null; try { System.out.println("JSON: " + json.toString()); String url = String.format("http://%s:%s%s?m=%s", host, port, path, URLEncoder.encode(json.toString(), "UTF-8")); System.out.println("url: " + url); hp = new HttpGet(url); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } StringBuilder sb = new StringBuilder(); try { HttpResponse r = httpClient.execute(hp); InputStreamReader is = new InputStreamReader(r.getEntity().getContent()); BufferedReader br = new BufferedReader(is); String line; while ((line = br.readLine()) != null) { System.out.println("response: " + line); sb.append(line); } } catch (IOException e) { MarietjeException tr = new MarietjeException("Connection stuk!" + e.getMessage()); this.exception = tr; throw tr; } JSONArray d = null; try { d = new JSONArray(new JSONTokener(sb.toString())); } catch (JSONException e) { throw (exception = new MarietjeException("Ja, JSON kapot!")); } if (d == null || d.length() != 3) throw (exception = new MarietjeException("Unexpected length of response list")); String token = null; JSONArray msgs = null; try { token = d.getString(0); msgs = d.getJSONArray(1); // JSONArray stream = d.getJSONArray(2); } catch (JSONException e) { throw (exception = new MarietjeException("unexpected format of response list")); } synchronized (this.outSemaphore) { String oldToken = this.token; this.token = token; if (oldToken == null) { this.outSemaphore.release(); } } for (int i = 0; i < msgs.length(); i++) { try { System.out.println("adding msg to queue"); synchronized (queueMessageIn) { this.queueMessageIn.add(msgs.getJSONObject(i)); } this.messageInSemaphore.release(); } catch (JSONException e) { System.err.println("ontvangen json kapot"); e.printStackTrace(); } } // TODO Streams left out. }
From source file:net.netheos.pcsapi.credentials.Credentials.java
/** * Create a Credential object from a JSON value. It detects automaticaly which credential is defined (OAuth or * password)// w ww. ja v a2s. c o m * * @param json The JSON to parse * @return The credentials object */ public static Credentials createFromJson(String json) { JSONObject jsonObj = (JSONObject) new JSONTokener(json).nextValue(); if (jsonObj.has(PasswordCredentials.PASSWORD)) { // Password credentials return PasswordCredentials.fromJson(jsonObj); } else { // OAuth2 credentials return OAuth2Credentials.fromJson(jsonObj); } }