List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:com.aokyu.dev.pocket.RetrieveResponse.java
public int getWordCount(String uid) throws JSONException { JSONObject obj = (JSONObject) get(uid); return obj.getInt(Parameter.WORD_COUNT); }
From source file:com.hichinaschool.flashcards.libanki.Tags.java
public void load(String json) { try {//from w w w .j a v a 2 s .c om JSONObject tags = new JSONObject(json); Iterator i = tags.keys(); while (i.hasNext()) { String t = (String) i.next(); mTags.put(t, tags.getInt(t)); } } catch (JSONException e) { throw new RuntimeException(e); } mChanged = false; }
From source file:org.lafs.hdfs.LAFS.java
private FileStatus getStatusFromJSON(JSONArray ja, Path path) throws IOException { FileStatus stat;//w ww . jav a 2 s . c om String flag; try { flag = ja.getString(0); boolean isDir = flag.equals("dirnode"); JSONObject data = ja.getJSONObject(1); long mtime = 0L; if (data.has("metadata")) mtime = (long) data.getJSONObject("metadata").getJSONObject("tahoe").getDouble("linkmotime"); // each file consists of 1 block of a size the entire length of the file long size = 0L; if (!isDir) { try { size = (long) data.getInt("size"); } catch (JSONException joe) { logger.warning("size was null"); } } //else // size = data.getJSONObject("children").length(); stat = new FileStatus(isDir ? 0 : size, isDir, 1, size, mtime, path); } catch (JSONException e) { logger.severe(ja.toString()); throw new IOException(e.getMessage()); } return stat; }
From source file:com.delaroystudios.weatherapp.utilities.OpenWeatherJsonUtils.java
/** * This method parses JSON from a web response and returns an array of Strings * describing the weather over various days from the forecast. * <p/>//from w ww . ja v a 2 s .c om * Later on, we'll be parsing the JSON into structured data within the * getFullWeatherDataFromJson function, leveraging the data we have stored in the JSON. For * now, we just convert the JSON into human-readable strings. * * @param forecastJsonStr JSON response from server * * @return Array of Strings describing weather data * * @throws JSONException If JSON data cannot be properly parsed */ public static String[] getSimpleWeatherStringsFromJson(Context context, String forecastJsonStr) throws JSONException { /* Weather information. Each day's forecast info is an element of the "list" array */ final String OWM_LIST = "list"; /* All temperatures are children of the "temp" object */ final String OWM_TEMPERATURE = "temp"; /* Max temperature for the day */ final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_MESSAGE_CODE = "cod"; /* String array to hold each day's weather String */ String[] parsedWeatherData = null; JSONObject forecastJson = new JSONObject(forecastJsonStr); /* Is there an error? */ if (forecastJson.has(OWM_MESSAGE_CODE)) { int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE); switch (errorCode) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: /* Location invalid */ return null; default: /* Server probably down */ return null; } } JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); parsedWeatherData = new String[weatherArray.length()]; long localDate = System.currentTimeMillis(); long utcDate = WeatherDateUtils.getUTCDateFromLocal(localDate); long startDay = WeatherDateUtils.normalizeDate(utcDate); for (int i = 0; i < weatherArray.length(); i++) { String date; String highAndLow; /* These are the values that will be collected */ long dateTimeMillis; double high; double low; String description; /* Get the JSON object representing the day */ JSONObject dayForecast = weatherArray.getJSONObject(i); /* * We ignore all the datetime values embedded in the JSON and assume that * the values are returned in-order by day (which is not guaranteed to be correct). */ dateTimeMillis = startDay + WeatherDateUtils.DAY_IN_MILLIS * i; date = WeatherDateUtils.getFriendlyDateString(context, dateTimeMillis, false); /* * Description is in a child array called "weather", which is 1 element long. * That element also contains a weather code. */ JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); /* * Temperatures are sent by Open Weather Map in a child object called "temp". * * Editor's Note: Try not to name variables "temp" when working with temperature. * It confuses everybody. Temp could easily mean any number of things, including * temperature, temporary and is just a bad variable name. */ JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); highAndLow = WeatherUtils.formatHighLows(context, high, low); parsedWeatherData[i] = date + " - " + description + " - " + highAndLow; } return parsedWeatherData; }
From source file:org.klnusbaum.udj.network.RESTProcessor.java
public static List<ActivePlaylistEntry> processActivePlaylist(JSONObject activePlaylist, AccountManager am, Account account, Context context) throws JSONException { checkPlaybackState(context, am, account, activePlaylist.getString("state")); checkVolume(context, am, account, activePlaylist.getInt("volume")); ActivePlaylistEntry currentSong = ActivePlaylistEntry.valueOf(activePlaylist.getJSONObject("current_song")); currentSong.setCurrentSong(true);//from w ww . j a v a2 s . c o m List<ActivePlaylistEntry> playlist = ActivePlaylistEntry .fromJSONArray(activePlaylist.getJSONArray("active_playlist")); playlist.add(0, currentSong); return playlist; }
From source file:wassilni.pl.navigationdrawersi.ui.Search.java
public void parseJSON(String s) { /*/*w w w . ja v a 2 s. c o m*/ * create 3 objects, one for driver, one for schedule and one for car * then parse the data into array of 3 arrays, their indices corresponds to the car/driver/schedule arrays * then present these data to the user in some order * this solution might not be the best, think of another solution!*/ String JSON_ARRAY = "result"; String s_id = "S_ID"; String sDate = "S_Start_date"; String eDate = "S_End_date"; String time = "S_time"; String mPrice = "monthPrice"; String dPrice = "dayPrice"; String BookedSeat = "BookedSeat"; String pickup = "pickup"; String dropoff = "dropoff"; String d_id = "D_ID"; String FName = "D_F_Name"; String LName = "D_L_Name"; String phoneNum = "D_phone"; String email = "D_Email"; String company = "company"; String license = "license"; String nationality = "nationality"; String female_companion = "female_companion"; String id_iqama = "id_iqama"; String age = "age"; String rating = "rating"; String confirmed = "confirmed"; String Plate_num = "Plate_num"; String C_company = "C_company"; String type = "type"; String model = "model"; String color = "color"; String capacity = "capacity"; String yearOfmanufacture = "yearOfmanufacture"; showDate(); /* * * this is how to parse values and then assign it to an array * public void parseJSON(String s)*/ try { JSONArray auser = null; JSONObject j = new JSONObject(s); auser = j.getJSONArray("result"); if (auser.length() > 0) { Driver d; schedule sched; Car car; for (int i = 0; i < auser.length(); i++) { JSONObject jsonObject = auser.getJSONObject(i); /** create schedule object **/ sched = new schedule(); sched.setS_ID(jsonObject.getInt(s_id)); sched.setStartDate(jsonObject.getString(sDate)); sched.setEndDate(jsonObject.getString(eDate)); sched.setTime(jsonObject.getString(time)); sched.setPickup(MyApp.getLatlng(jsonObject.getString(pickup))); sched.setDropoff(MyApp.getLatlng(jsonObject.getString(dropoff))); sched.setBookedSeat(jsonObject.getInt(BookedSeat)); sched.setMontPrice(jsonObject.getInt(mPrice)); sched.setDayPrice(jsonObject.getInt(dPrice)); /** create car object **/ car = new Car(); car.setPlate(jsonObject.getString(Plate_num)); car.setType(jsonObject.getString(type)); car.setModel(jsonObject.getString(model)); car.setColor(jsonObject.getString(color)); car.setCompany(jsonObject.getString(C_company)); car.setCapacity(jsonObject.getInt(capacity)); car.setYearOfManufacture(jsonObject.getInt(yearOfmanufacture)); /** create driver object **/ System.out.println(); d = new Driver(); d.setID(jsonObject.getInt(d_id)); d.setEmail(jsonObject.getString(email)); d.setFName(jsonObject.getString(FName)); d.setLName(jsonObject.getString(LName)); d.setPhone(jsonObject.getString(phoneNum)); d.setCompany(jsonObject.getString(company)); d.setLicense(jsonObject.getString(license)); d.setNationality(jsonObject.getString(nationality)); d.setFemaleCompanion(jsonObject.getString(female_companion).charAt(0)); d.setID_Iqama(jsonObject.getString(id_iqama)); d.setAge(jsonObject.getString(age)); d.setRating(jsonObject.getDouble(rating)); d.setConfirmed(jsonObject.getString(confirmed).charAt(0)); d.setCar(car); // d.getSchedule().add(sched); // drivers.add(d); searchResult searchR = new searchResult(d, sched); searchResults.add(searchR); /* int D_id =jsonObject.getInt(d_id); boolean flag = true; for(int a=0;a<drivers.size();a++){ if(drivers.get(a).getID()==D_id){ drivers.get(a).setCar(car); drivers.get(a).getSchedule().add(sched); flag=false; break; } }*/ //schedules.add(sched); /* if(flag) { System.out.println(); d = new Driver(); d.setID(jsonObject.getInt(d_id)); d.setEmail(jsonObject.getString(email)); d.setFName(jsonObject.getString(FName)); d.setLName(jsonObject.getString(LName)); d.setPhone(jsonObject.getString(phoneNum)); d.setCompany(jsonObject.getString(company)); d.setLicense(jsonObject.getString(license)); d.setNationality(jsonObject.getString(nationality)); d.setFemaleCompanion(jsonObject.getString(female_companion).charAt(0)); d.setID_Iqama(jsonObject.getString(id_iqama)); d.setAge(jsonObject.getString(age)); d.setRating(jsonObject.getDouble(rating)); d.setConfirmed(jsonObject.getString(confirmed).charAt(0)); d.setCar(car); d.getSchedule().add(sched); drivers.add(d); }*/ } //end for auser.length } // if JSON EMPTY else Toast.makeText(getApplicationContext(), " ?", Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } // for (int i=0 ; i< drivers.size();i++) // System.out.println(drivers.get(i).toString()+"\t"+schedules.get(i).getS_ID()); }
From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java
/** * writes channel LUTs and display ranges for composite mode Could also be * expanded to write ROIs, file info, slice labels, and overlays */// w w w . j av a2 s . c om private void writeImageJMetadata(int numChannels, String summaryComment) throws IOException { String info = summaryMDString_; if (summaryComment != null && summaryComment.length() > 0) { info = "Acquisition comments: \n" + summaryComment + "\n\n\n" + summaryMDString_; } //size entry (4 bytes) + 4 bytes file info size + 4 bytes for channel display //ranges length + 4 bytes per channel LUT int mdByteCountsBufferSize = 4 + 4 + 4 + 4 * numChannels; int bufferPosition = 0; ByteBuffer mdByteCountsBuffer = ByteBuffer.allocate(mdByteCountsBufferSize).order(BYTE_ORDER); //nTypes is number actually written among: fileInfo, slice labels, display ranges, channel LUTS, //slice labels, ROI, overlay, and # of extra metadata entries int nTypes = 3; //file info, display ranges, and channel LUTs int mdBufferSize = 4 + nTypes * 8; //Header size: 4 bytes for magic number + 8 bytes for label (int) and count (int) of each type mdByteCountsBuffer.putInt(bufferPosition, 4 + nTypes * 8); bufferPosition += 4; //2 bytes per a character of file info mdByteCountsBuffer.putInt(bufferPosition, 2 * info.length()); bufferPosition += 4; mdBufferSize += info.length() * 2; //display ranges written as array of doubles (min, max, min, max, etc) mdByteCountsBuffer.putInt(bufferPosition, numChannels * 2 * 8); bufferPosition += 4; mdBufferSize += numChannels * 2 * 8; for (int i = 0; i < numChannels; i++) { //768 bytes per LUT mdByteCountsBuffer.putInt(bufferPosition, 768); bufferPosition += 4; mdBufferSize += 768; } //Header (1) File info (1) display ranges (1) LUTS (1 per channel) int numMDEntries = 3 + numChannels; ByteBuffer ifdCountAndValueBuffer = ByteBuffer.allocate(8).order(BYTE_ORDER); ifdCountAndValueBuffer.putInt(0, numMDEntries); ifdCountAndValueBuffer.putInt(4, (int) filePosition_); fileChannel_.write(ifdCountAndValueBuffer, ijMetadataCountsTagPosition_ + 4); fileChannel_.write(mdByteCountsBuffer, filePosition_); filePosition_ += mdByteCountsBufferSize; //Write metadata types and counts ByteBuffer mdBuffer = ByteBuffer.allocate(mdBufferSize).order(BYTE_ORDER); bufferPosition = 0; //All the ints declared below are non public field in TiffDecoder final int ijMagicNumber = 0x494a494a; mdBuffer.putInt(bufferPosition, ijMagicNumber); bufferPosition += 4; //Write ints for each IJ metadata field and its count final int fileInfo = 0x696e666f; mdBuffer.putInt(bufferPosition, fileInfo); bufferPosition += 4; mdBuffer.putInt(bufferPosition, 1); bufferPosition += 4; final int displayRanges = 0x72616e67; mdBuffer.putInt(bufferPosition, displayRanges); bufferPosition += 4; mdBuffer.putInt(bufferPosition, 1); bufferPosition += 4; final int luts = 0x6c757473; mdBuffer.putInt(bufferPosition, luts); bufferPosition += 4; mdBuffer.putInt(bufferPosition, numChannels); bufferPosition += 4; //write actual metadata //FileInfo for (char c : info.toCharArray()) { mdBuffer.putChar(bufferPosition, c); bufferPosition += 2; } try { JSONArray channels = masterMPTiffStorage_.getDisplayAndComments().getJSONArray("Channels"); JSONObject channelSetting; for (int i = 0; i < numChannels; i++) { channelSetting = channels.getJSONObject(i); //Display Ranges: For each channel, write min then max mdBuffer.putDouble(bufferPosition, channelSetting.getInt("Min")); bufferPosition += 8; mdBuffer.putDouble(bufferPosition, channelSetting.getInt("Max")); bufferPosition += 8; } //LUTs for (int i = 0; i < numChannels; i++) { channelSetting = channels.getJSONObject(i); LUT lut = ImageUtils.makeLUT(new Color(channelSetting.getInt("Color")), channelSetting.getDouble("Gamma")); for (byte b : lut.getBytes()) { mdBuffer.put(bufferPosition, b); bufferPosition++; } } } catch (JSONException ex) { ReportingUtils.logError( "Problem with displayAndComments: Couldn't write ImageJ display settings as a result"); } ifdCountAndValueBuffer = ByteBuffer.allocate(8).order(BYTE_ORDER); ifdCountAndValueBuffer.putInt(0, mdBufferSize); ifdCountAndValueBuffer.putInt(4, (int) filePosition_); fileChannel_.write(ifdCountAndValueBuffer, ijMetadataTagPosition_ + 4); fileChannel_.write(mdBuffer, filePosition_); filePosition_ += mdBufferSize; }
From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java
private String getIJDescriptionString() { StringBuffer sb = new StringBuffer(); sb.append("ImageJ=" + "1.4\n"); if (numChannels_ > 1) { sb.append("channels=" + numChannels_ + "\n"); }/* w ww . j a v a2 s .c o m*/ if (numSlices_ > 1) { sb.append("slices=" + numSlices_ + "\n"); } if (numFrames_ > 1) { sb.append("frames=" + numFrames_ + "\n"); } if (numFrames_ > 1 || numSlices_ > 1 || numChannels_ > 1) { sb.append("hyperstack=true\n"); } if (numChannels_ > 1 && numSlices_ > 1 && masterMPTiffStorage_.slicesFirst()) { sb.append("order=zct\n"); } //cm so calibration unit is consistent with units used in Tiff tags sb.append("unit=um\n"); if (numSlices_ > 1) { sb.append("spacing=" + zStepUm_ + "\n"); } //write single channel contrast settings or display mode if multi channel try { JSONObject channel0setting = masterMPTiffStorage_.getDisplayAndComments().getJSONArray("Channels") .getJSONObject(0); if (numChannels_ == 1) { double min = channel0setting.getInt("Min"); double max = channel0setting.getInt("Max"); sb.append("min=" + min + "\n"); sb.append("max=" + max + "\n"); } else { int displayMode = channel0setting.getInt("DisplayMode"); //COMPOSITE=1, COLOR=2, GRAYSCALE=3 if (displayMode == 1) { sb.append("mode=composite\n"); } else if (displayMode == 2) { sb.append("mode=color\n"); } else if (displayMode == 3) { sb.append("mode=gray\n"); } } } catch (JSONException ex) { } sb.append((char) 0); return new String(sb); }
From source file:com.google.walkaround.wave.server.attachment.AttachmentMetadata.java
private ImageMetadata createImageMetadata(String key) { final JSONObject imgData; try {/*w w w.j a v a 2 s . c o m*/ imgData = getMetadata().has(key) ? getMetadata().getJSONObject(key) : null; } catch (JSONException e) { throw new Error(e); } if (imgData == null) { return null; } return new ImageMetadata() { @Override public int getWidth() { try { return imgData.getInt("width"); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public int getHeight() { try { return imgData.getInt("height"); } catch (JSONException e) { throw new RuntimeException(e); } } }; }
From source file:com.prashantpal.sunshine.app.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us.// ww w . j a v a 2 s . c o m */ private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); int inserted = 0; for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } }