List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java
public PushData(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException { super(_randoms, PacketType.PUSH_DATA); _raw.order(ByteOrder.LITTLE_ENDIAN); if (_raw.remaining() < 8) { throw new MalformedPacketException("too short"); }//from ww w .j a v a2 s . c om gatewayEui = new byte[8]; _raw.get(gatewayEui); byte[] json = new byte[_raw.remaining()]; _raw.get(json); JSONObject jo; try { jo = new JSONObject(new String(json)); } catch (JSONException ex) { throw new MalformedPacketException("malformed json"); } stats = new ArrayList<>(); rxpks = new ArrayList<>(); if (jo.has("rxpk")) { if (!jo.get("rxpk").getClass().equals(JSONArray.class)) { throw new MalformedPacketException("malformed json (rxpk)"); } JSONArray rxpk = jo.getJSONArray("rxpk"); for (int i = 0; i < rxpk.length(); i++) { rxpks.add(new Rxpk(rxpk.getJSONObject(i))); } } if (jo.has("stat")) { if (!jo.get("stat").getClass().equals(JSONArray.class)) { throw new MalformedPacketException("malformed json (stat)"); } JSONArray stat = jo.getJSONArray("stat"); for (int i = 0; i < stat.length(); i++) { stats.add(new Stat(stat.getJSONObject(i))); } } }
From source file:com.jjoseba.podemosquotes.model.JSONReader.java
public ArrayList<Quote> parse() { String contentsJson = readJSONFile(); HashMap<String, QuoteAuthor> authors = new HashMap<>(); ArrayList<Quote> quotes = new ArrayList<>(); try {//from w w w .ja v a 2 s . co m JSONObject json = new JSONObject(contentsJson); JSONArray authorsArray = json.getJSONArray("authors"); for (int i = 0; i < authorsArray.length(); ++i) { JSONObject auth = (JSONObject) authorsArray.get(i); QuoteAuthor author = new QuoteAuthor(); author.setName(auth.getString("name")); author.setImagePath(auth.getString("image")); author.setPosition(auth.getString("position")); authors.put(auth.getString("id"), author); } JSONArray quotesArray = json.getJSONArray("quotes"); for (int i = 0; i < quotesArray.length(); ++i) { JSONObject q = (JSONObject) quotesArray.get(i); Quote quote = new Quote(); quote.setQuote(q.getString("quote")); quote.setSoundPath(q.getString("sound")); quote.setAuthor(authors.get(q.getString("author"))); quotes.add(quote); } } catch (JSONException e) { e.printStackTrace(); } return quotes; }
From source file:net.olejon.mdapp.LvhCategoriesAdapter.java
@Override public void onBindViewHolder(CategoryViewHolder viewHolder, int i) { try {//from w w w . j ava 2 s. c om final JSONObject categoriesJsonObject = mCategories.getJSONObject(i); viewHolder.card.setCardBackgroundColor(Color.parseColor(mColor)); switch (mIcon) { case "lvh_urgent": { viewHolder.icon.setImageResource(R.drawable.ic_favorite_white_24dp); break; } case "lvh_symptoms": { viewHolder.icon.setImageResource(R.drawable.ic_stethoscope); break; } case "lvh_injuries": { viewHolder.icon.setImageResource(R.drawable.ic_healing_white_24dp); break; } case "lvh_administrative": { viewHolder.icon.setImageResource(R.drawable.ic_my_library_books_white_24dp); break; } } viewHolder.title.setText(categoriesJsonObject.getString("title")); viewHolder.categories.removeAllViews(); final JSONArray itemsJsonArray = categoriesJsonObject.getJSONArray("items"); for (int f = 0; f < itemsJsonArray.length(); f++) { final JSONObject categoryJsonObject = itemsJsonArray.getJSONObject(f); final String name = categoryJsonObject.getString("name"); final String uri = categoryJsonObject.getString("uri"); TextView textView = (TextView) mLayoutInflater .inflate(R.layout.activity_lvh_categories_card_categories_item, null); textView.setText(name); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, MainWebViewActivity.class); intent.putExtra("title", name); intent.putExtra("uri", uri); mContext.startActivity(intent); } }); viewHolder.categories.addView(textView); } animateView(viewHolder.card, i); } catch (Exception e) { Log.e("LvhCategoriesAdapter", Log.getStackTraceString(e)); } }
From source file:app.com.example.android.sunshine.ForecastFragment.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.//www. j a va2 s .com */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DATETIME = "dt"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); String[] resultStrs = new String[numDays]; for (int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime = dayForecast.getLong(OWM_DATETIME); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // 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); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } return resultStrs; }
From source file:com.mikecorrigan.trainscorekeeper.Game.java
public boolean read(final Context context) { Log.vc(VERBOSE, TAG, "read: context=" + context); String path = context.getFilesDir() + File.separator + SAVED_FILE; File file = new File(path); JSONObject jsonRoot = JsonUtils.readFromFile(file); if (jsonRoot == null) { Log.e(TAG, "read: failed to read root"); return false; }/*from w w w .j av a 2 s. c o m*/ scoreEvents.clear(); lastScoreEvent = 0; try { spec = jsonRoot.getString(JsonSpec.GAME_SPEC); JSONArray jsonScoreEvents = jsonRoot.getJSONArray(JsonSpec.SCORES_KEY); for (int i = 0; i < jsonScoreEvents.length(); i++) { JSONObject jsonScoreEvent = jsonScoreEvents.getJSONObject(i); ScoreEvent scoreEvent = new ScoreEvent(jsonScoreEvent); scoreEvents.add(scoreEvent); notifyEnabled(scoreEvent.getPlayerId(), true); } } catch (JSONException e) { Log.th(TAG, e, "read: parse failed"); return false; } lastScoreEvent = scoreEvents.size(); notifyListeners(); return true; }
From source file:com.dvd.ui.UpdateBooking.java
private void getData() { try {//www . j a v a 2 s . com if (isServiceOn) { String result = ""; String url1 = "http://localhost:8080/getBooking"; // String q = URLEncoder.encode(original, "UTF-8"); URL url = new URL(url1); URL obj = url; HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result result = response.toString(); // Parse to get translated text JSONObject jsonObject = new JSONObject(result); JSONArray bookingJsonList = jsonObject.getJSONArray("body"); List<Booking> list = new ArrayList<>(); if (bookingJsonList != null) { for (int i = 0; i < bookingJsonList.length(); i++) { JSONObject c = bookingJsonList.getJSONObject(i); int id = c.getInt("id"); int copyNum = c.getInt("copyNumber"); int userId = c.getInt("userID"); String da = c.getString("bookingAddedDate"); Booking d = new Booking(); d.setBookingAddedDate(da); d.setUserID(userId); d.setCopyNumber(copyNum); d.setId(id); System.out.println(d); list.add(d); } bookingList = list; } } else { BookingRepository repository = new BookingRepository(); List<BookingDao> s = repository.getBookingList(); if (s != null) { bookingList = new ArrayList<Booking>(); for (BookingDao bookingDao : s) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); // Using DateFormat format method we can create a string // representation of a date with the defined format. String dateAdded = df.format(bookingDao.getBookingAddedDate()); bookingList.add(new Booking(bookingDao.getId(), bookingDao.getCopyNumber(), bookingDao.getUserID(), dateAdded)); } } } } catch (Exception e) { System.out.println(e); } }
From source file:com.example.quadros_10084564.sunshine_v2.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./*from ww w . j a v a2s . 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(); 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); } int inserted = 0; // add to database if (cVVector.size() > 0) { 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(); } }
From source file:com.hotstar.player.adplayer.feeds.ReferencePlayerFeedAdapter.java
/** * Returns an instance of the ReferencePlayerFeedAdapter after parsing the * JSON feed/*w w w .j av a 2s.c om*/ * * @param jsonFeed * - feed response in JSON format to be parsed * @return ReferencePlayerFeedAdapter - an instance of the * ReferencePlayerFeedAdapter that will iterate through the JSON * content list response * @throws FeedParsingException * - if there is an error parsing the JSON feed */ public static ReferencePlayerFeedAdapter getInstance(String jsonFeed) throws FeedParsingException { if (jsonFeed == null) { return null; } try { JSONObject object = new JSONObject(jsonFeed); JSONArray entries = object.getJSONArray(NAME_ENTRIES); return new ReferencePlayerFeedAdapter(entries); } catch (JSONException e) { AdVideoApplication.logger.e(LOG_TAG + "::getInstance", "Error parsing content list: " + e.getMessage()); throw new FeedParsingException(); } }
From source file:com.aliyun.openservices.odps.console.commands.logview.GetTaskDetailsAction.java
private List<FuxiJob> loadJobsFromStream(InputStream in) throws ODPSConsoleException { JSONTokener tokener = new JSONTokener(new BufferedReader(new InputStreamReader(in))); try {/*from w w w.j a va 2 s.c om*/ JSONObject obj = new JSONObject(tokener); ArrayList<FuxiJob> jobs = new ArrayList<FuxiJob>(); JSONObject mapReduceJson; try { mapReduceJson = obj.getJSONObject("mapReduce"); } catch (JSONException e) { return jobs; } JSONArray jobsJson = mapReduceJson.getJSONArray("jobs"); for (int i = 0; i < jobsJson.length(); i++) { jobs.add(getFuxiJobFromJson(jobsJson.getJSONObject(i))); } return jobs; } catch (JSONException e) { e.printStackTrace(); throw new ODPSConsoleException("Bad json format"); } }
From source file:com.aliyun.openservices.odps.console.commands.logview.GetTaskDetailsAction.java
private FuxiJob getFuxiJobFromJson(JSONObject jobJson) throws JSONException { FuxiJob job = new FuxiJob(); job.name = jobJson.getString("name"); job.tasks = new ArrayList<FuxiTask>(); JSONArray tasksJson = jobJson.getJSONArray("tasks"); for (int i = 0; i < tasksJson.length(); i++) { job.tasks.add(getFuxiTaskFromJson(tasksJson.getJSONObject(i))); }/*from w w w . j av a2 s . com*/ return job; }