private void parseCity(String result) { try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject jb = jArray.getJSONObject(i); String cityId = jb.getString("CITYID"); String cityName = jb.getString("CITYNAME"); cityNameId.put(cityName, cityId); } serializeCity(cityNameId); setAdapter(); } catch (Exception e) { // TODO: handle exception } }
@Override public List<RepositoryContentDataEntry> loadInBackground() { if (isRepoReady) { String uri = getContext().getString(R.string.url_repo_content, userName, repoName, path); FetchHTTPConnectionService fetchHTTPConnectionService = new FetchHTTPConnectionService(uri, getContext()); HTTPConnectionResult result = fetchHTTPConnectionService.establishConnection(); if (result == null) { return null; } try { JSONArray jsonArray = new JSONArray(result.getResult()); return new RepoContentParser().parse(jsonArray); } catch (JSONException e) { Log.e(TAG, "Parse Error ", e); Bundle bundle = new Bundle(); bundle.putString(TAG, Utils.getStackTrace(e)); firebaseAnalytics.logEvent(fbAEvent, bundle); } } return null; }
/** * @param apiTag tag to uniquely distinguish Volley requests. Null is allowed * @param url URL to fetch the string at * @param httpMethod the request method to use (GET or POST) * @param params A {@link JSONArray} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param headers optional Http headers * @param serverCallback Listener to receive the String response */ public void placeJsonArrayRequest(@Nullable final String apiTag, String url, int httpMethod, @Nullable JSONArray params, final @Nullable HashMap<String, String> headers, final ServerCallback serverCallback) { Request request = new JsonArrayRequest(httpMethod, url, params, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { serverCallback.onAPIResponse(apiTag, response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { serverCallback.onErrorResponse(apiTag, error); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { return headers != null ? headers : super.getHeaders(); } }; request.setRetryPolicy(retryPolicy); addToRequestQueue(request); }
public synchronized Fallback a(JSONObject jSONObject) { this.a = jSONObject.optString(c.a); this.n = jSONObject.getLong("ttl"); this.l = jSONObject.getDouble("pct"); this.i = jSONObject.getLong(DeviceInfo.TAG_TIMESTAMPS); this.d = jSONObject.optString("city"); this.c = jSONObject.optString("prv"); this.g = jSONObject.optString("cty"); this.e = jSONObject.optString("isp"); this.f = jSONObject.optString("ip"); this.b = jSONObject.optString(com.alipay.sdk.cons.c.f); this.h = jSONObject.optString("xf"); JSONArray jSONArray = jSONObject.getJSONArray("fbs"); for (int i = 0; i < jSONArray.length(); i++) { a(new e().a(jSONArray.getJSONObject(i))); } return this; }
@Deprecated public Score[] getScores(int beatMapID, GameMode gameMode, int amount, String userName) throws JSONException, MalformedURLException, IOException{ if(amount > 100) amount = 100; if(amount < 1) amount = 1; StringBuilder sb = new StringBuilder(); sb.append("https://osu.ppy.sh/api/get_scores?"); sb.append("k=" + getAPIkey()); sb.append("&b=" + beatMapID); sb.append("&m=" + gameMode.ordinal()); sb.append("&limit=" + amount); sb.append("&u=" + userName); sb.append("&type=string"); JSONArray scoresArray = new JSONArray(StringUtils.getStringFromWebsite(sb.toString())); Score[] scores = new Score[scoresArray.length()]; for(int i = 0; i < scoresArray.length(); i++){ scores[i] = new Score(scoresArray.getJSONObject(i)); } return scores; }
/** * Retorna a lista de boletos emitidos por códigos de pedidos * @param pedidos: Lista de códigos de pedidos os quais deseja retornar os boletos * @return String: Link contendo os boletos relacionados aos códigos de pedidos enviados */ public String getByIds(Set<String> pedidos) throws IOException, PJBankException { PJBankClient client = new PJBankClient(this.endPoint.concat("/transacoes/lotes")); HttpPost httpPost = client.getHttpPostClient(); httpPost.addHeader("x-chave", this.getChave()); JSONArray pedidosArray = new JSONArray(pedidos); JSONObject params = new JSONObject(); params.put("pedido_numero", pedidosArray); httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8)); String response = EntityUtils.toString(client.doRequest(httpPost).getEntity()); JSONObject responseObject = new JSONObject(response); return responseObject.getString("linkBoleto"); }
public void testCreateThumbnailInReadonlyMode() throws Exception { createUser(USER_ALFRESCO); AuthenticationUtil.setFullyAuthenticatedUser(USER_ALFRESCO); this.transactionService.setAllowWrite(false); // do pdfToSWF transformation in read-only if (this.contentService.getTransformer(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_FLASH) != null) { // in share creation of thumbnail for webpreview is forced String url = "/api/node/" + pdfNode.getStoreRef().getProtocol() + "/" + pdfNode.getStoreRef().getIdentifier() + "/" + pdfNode.getId() + "/content/thumbnails/webpreview?c=force"; JSONObject tn = new JSONObject(); tn.put("thumbnailName", "webpreview"); sendRequest(new GetRequest(url), 200, USER_ALFRESCO); } this.transactionService.setAllowWrite(true); // Check getAll whilst we are here Response getAllResp = sendRequest(new GetRequest(getThumbnailsURL(jpgNode)), 200); JSONArray getArr = new JSONArray(getAllResp.getContentAsString()); assertNotNull(getArr); assertEquals(0, getArr.length()); }
/** * 解析处理服务器返回的县级数据 * @param response * @return */ public static boolean handleCountyResponse(String response,int cityId){ if(!TextUtils.isEmpty(response)){ try { JSONArray allCountys = new JSONArray(response); for (int i = 0; i < allCountys.length(); i++) { JSONObject countyJSONObject = allCountys.getJSONObject(i); County county = new County(); county.setWeathreId(countyJSONObject.getString("weather_id")); county.setCountyName(countyJSONObject.getString("name")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; }
public static StatisticsEvent fromJSONObject(JSONObject eventObject) { StatisticsEvent statisticsEvent = new StatisticsEvent(); statisticsEvent.setKey(eventObject.optString(KEY)); statisticsEvent.setValue(eventObject.optString(VALUE)); statisticsEvent.setTime(eventObject.optString(TIME)); statisticsEvent.setType(eventObject.optString(TYPE)); try { JSONArray jsonArray = eventObject.optJSONArray(EXTENDS); if (jsonArray != null) { statisticsEvent.setExtendList(JsonUtil.toList(jsonArray.toString(), Extend.class)); } } catch (JSONException e) { e.printStackTrace(); } return statisticsEvent; }
public static String parseIatResult(String json) { StringBuffer ret = new StringBuffer(); try { JSONTokener tokener = new JSONTokener(json); JSONObject joResult = new JSONObject(tokener); JSONArray words = joResult.getJSONArray("ws"); for (int i = 0; i < words.length(); i++) { // 转写结果词,默认使用第一个结果 JSONArray items = words.getJSONObject(i).getJSONArray("cw"); JSONObject obj = items.getJSONObject(0); ret.append(obj.getString("w")); // 如果需要多候选结果,解析数组其他字段 // for(int j = 0; j < items.length(); j++) // { // JSONObject obj = items.getJSONObject(j); // ret.append(obj.getString("w")); // } } } catch (Exception e) { e.printStackTrace(); } return ret.toString(); }
@Override public List<ReposDataEntry> loadInBackground() { String uri = getContext().getString(R.string.url_repos, page); FetchHTTPConnectionService fetchHTTPConnectionService = new FetchHTTPConnectionService(uri, getContext()); HTTPConnectionResult result = fetchHTTPConnectionService.establishConnection(); Log.v(TAG, "responseCode = " + result.getResponceCode()); Log.v(TAG, "result = " + result.getResult()); try { JSONArray jsonArray = new JSONArray(result.getResult()); return new ReposParser().parse(jsonArray); } catch (JSONException e) { Log.e(TAG, "", e); } return null; }
@Override protected byte[] getBody(Context context) { byte[] array = new byte[0]; JSONObject body = new JSONObject(); try { body.put("network_id", params.getNetworkId()); body.put("zone_id", params.getZoneId()); body.put("user_id", params.getUserId()); List<String> stringList = new ArrayList<>(Arrays.asList(params.getKeywords())); body.put("keywords", new JSONArray(stringList)); if(params.getWidth() != null) body.put("width", params.getWidth()); if(params.getHeight() != null) body.put("height", params.getHeight()); array = body.toString().getBytes("UTF-8"); } catch (JSONException | UnsupportedEncodingException e) { e.printStackTrace(); } return array; }
public static void b(Context context, JSONObject jSONObject) { try { JSONArray jSONArray = new JSONArray(); jSONArray.put(jSONObject); JSONObject jSONObject2 = new JSONObject(); jSONObject2.put(z[6], jSONArray); if (a(jSONObject2, context)) { new StringBuilder(z[7]).append(jSONObject.toString()); z.b(); if (p.a(context, jSONObject2, true) == 200) { z.b(); } } } catch (JSONException e) { } catch (Exception e2) { } }
/** * This is used in Put command this method uses HashSet as default implementation * * @param value * @param parameterType * @return setValue * @throws GfJsonException */ @SuppressWarnings({"rawtypes", "unchecked"}) private static Object toSet(Object value, Class<?> parameterType) throws GfJsonException { try { JSONArray array = (JSONArray) value; Set set = new HashSet(); for (int i = 0; i < array.length(); i++) { Object element = array.get(i); if (isPrimitiveOrWrapper(element.getClass())) { set.add(element); } else throw new GfJsonException( "Only primitive types are supported in set type for input commands"); } return set; } catch (JSONException e) { throw new GfJsonException(e); } }
@Override public SmsStatusPullCallbackResult parseFromHTTPResponse(HTTPResponse response) throws JSONException { JSONObject json = parseToJson(response); result = json.getInt("result"); errMsg = json.getString("errmsg"); if (result == 0) { count = json.getInt("count"); if (!json.isNull("data")) { JSONArray data = json.getJSONArray("data"); for (int i = 0; i < data.length(); i++) { callbacks.add((new Callback()).parse(data.getJSONObject(i))); } } } return this; }
/** * Read the list of files from this directory. * * @return a JSONArray containing JSONObjects that represent Entry objects. * @throws FileNotFoundException if the directory is not found. * @throws JSONException * @throws MalformedURLException */ private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException { try { LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); Filesystem fs = this.filesystemForURL(inputURL); if (fs == null) { throw new MalformedURLException("No installed handlers for this URL"); } return fs.readEntriesAtLocalURL(inputURL); } catch (IllegalArgumentException e) { MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); mue.initCause(e); throw mue; } }
private static FetchedAppSettings parseAppSettingsFromJSON( String applicationId, JSONObject settingsJSON) { JSONArray errorClassificationJSON = settingsJSON.optJSONArray(APP_SETTING_ANDROID_SDK_ERROR_CATEGORIES); FacebookRequestErrorClassification errorClassification = errorClassificationJSON == null ? FacebookRequestErrorClassification.getDefaultErrorClassification() : FacebookRequestErrorClassification.createFromJSON( errorClassificationJSON ); FetchedAppSettings result = new FetchedAppSettings( settingsJSON.optBoolean(APP_SETTING_SUPPORTS_IMPLICIT_SDK_LOGGING, false), settingsJSON.optString(APP_SETTING_NUX_CONTENT, ""), settingsJSON.optBoolean(APP_SETTING_NUX_ENABLED, false), parseDialogConfigurations(settingsJSON.optJSONObject(APP_SETTING_DIALOG_CONFIGS)), errorClassification ); fetchedAppSettings.put(applicationId, result); return result; }
public JSONArray fetchByRange(Thing start, Thing end) { long initialId2Decimal = Long.parseLong(start.getId(), 36); long finalId2Decimal = Long.parseLong(end.getId(), 36); String startFullname = start.getFullName(); JSONArray concatenatedChildren = new JSONArray(); while (initialId2Decimal < finalId2Decimal) { int range = Math.min(RedditAPIUtils.MAX_MODELS_LIMIT, Math.toIntExact(finalId2Decimal - initialId2Decimal)); /** fetchByFullnames(startFullname, range) returns (startFullname+1, startFullname+2, .....), in this case * we want ((startFullname, startFullname+1, .....)) so we decrease the start full name by one. **/ JSONArray currentChildren = fetchByFullnames(ModelsUtils.decreaseFullnameByOne(startFullname), range); String lastFullname = ModelsUtils.extractLastFullname(currentChildren); if (lastFullname == null || lastFullname == "") continue; startFullname = lastFullname; initialId2Decimal += range; concatenatedChildren = JSONArrayUtils.concatArray(concatenatedChildren, currentChildren); } return concatenatedChildren; }
public SupportedDownloads(Context context) { try { String json = Utils.existFile(context.getFilesDir() + "/downloads.json") ? Utils.readFile(context.getFilesDir() + "/downloads.json", false) : Utils.readAssetFile(context, "downloads.json"); JSONArray devices = new JSONArray(json); for (int i = 0; i < devices.length(); i++) { JSONObject device = devices.getJSONObject(i); JSONArray vendors = device.getJSONArray("vendor"); for (int x = 0; x < vendors.length(); x++) { if (vendors.getString(x).equals(Device.getVendor())) { JSONArray names = device.getJSONArray("device"); for (int y = 0; y < names.length(); y++) { if (names.getString(y).equals(Device.getDeviceName())) { mLink = device.getString("link"); } } } } } } catch (JSONException e) { Utils.toast("Failed to read downloads.json " + e.getMessage(), context); } }
public static ArrayList<Bookmarks> getBookmarks() { String bookmarks = getString("maki_bookmarks", "[]"); ArrayList<Bookmarks> listBookmarks = new ArrayList<>(); try { JSONArray array = new JSONArray(bookmarks); for (int i = 0; i < array.length(); i++) { JSONObject ob = array.getJSONObject(i); Bookmarks bookmark = new Bookmarks(); bookmark.setTitle(ob.getString("title")); bookmark.setUrl(ob.getString("url")); listBookmarks.add(bookmark); } } catch (JSONException e) { e.printStackTrace(); } return listBookmarks; }
@Override public Object finalItem() { if (_content != null) { String content = _content.trim(); _content = null; try { Object jsonObj = new JSONTokener(content).nextValue(); if (jsonObj instanceof JSONObject || jsonObj instanceof JSONArray) { parseJsonObject(jsonObj, this, null); content = null; } } catch (JSONException e) { } if (!TextUtils.isEmpty(content)) { _binding._dataUrl = content; } } XulBinding binding = _binding; FinalCallback<XulBinding> callback = _callback; _Builder.recycle(this); callback.onFinal(binding); return binding; }
@Override public Integer valueFromObject(Object object, float scale) { JSONArray colorArray = (JSONArray) object; if (colorArray.length() == 4) { boolean shouldUse255 = true; for (int i = 0; i < colorArray.length(); i++) { double colorChannel = colorArray.optDouble(i); if (colorChannel > 1f) { shouldUse255 = false; } } float multiplier = shouldUse255 ? 255f : 1f; return Color.argb( (int) (colorArray.optDouble(3) * multiplier), (int) (colorArray.optDouble(0) * multiplier), (int) (colorArray.optDouble(1) * multiplier), (int) (colorArray.optDouble(2) * multiplier)); } return Color.BLACK; }
public DialogOutput(JSONObject json) { mGuid = json.optString(Keys.Guid); mText = json.optString(Keys.Text); mAudioUri = json.optString(Keys.Uri); mVideoUri = json.optString(Keys.VideoFile); mCharacter = json.optString(Keys.Character); mDuration = json.optDouble(Keys.Duration, 0); mUserData = json.optString(Keys.UserData); JSONArray phonemeJson = json.optJSONArray(Keys.Phonemes); if (phonemeJson != null && phonemeJson.length() > 0) { mPhonemes = new ArrayList<>(); for (int i = 0; i < phonemeJson.length(); i++) { JSONObject p = phonemeJson.optJSONObject(i); if (p != null) { Phoneme phoneme = new Phoneme(p); mPhonemes.add(phoneme); } } } }
private void parseItems(List<GalleryItem> items, JSONObject jsonBody) throws IOException, JSONException { JSONObject photosJsonObject = jsonBody.getJSONObject("photos"); JSONArray photoJsonArray = photosJsonObject.getJSONArray("photo"); for (int i = 0; i < photoJsonArray.length(); i++) { JSONObject photoJsonObject = photoJsonArray.getJSONObject(i); GalleryItem item = new GalleryItem(); item.setId(photoJsonObject.getString("id")); item.setCaption(photoJsonObject.getString("title")); if (!photoJsonObject.has("url_s")) { continue; } item.setUrl(photoJsonObject.getString("url_s")); items.add(item); } }
/** * Convert a JSONObject to a HashMap * * @param object the JSON Object * @return the HashMap converted * @throws JSONException when json is wrong */ public static HashMap<String, Object> toMap(JSONObject object) throws JSONException { HashMap<String, Object> map = new HashMap<>(); Iterator<String> keysItr = object.keys(); while (keysItr.hasNext()) { String key = keysItr.next(); Object value = object.get(key); if (value instanceof JSONArray) { value = toList((JSONArray) value); } else if (value instanceof JSONObject) { value = toMap((JSONObject) value); } map.put(key, value); } return map; }
public void assertContentDuplicates() throws Throwable { siw(new Runnable() { @Override public void run() { tabbedPane = (JTabbedPane) ComponentUtils.findComponent(JTabbedPane.class, frame); tabbedPane.setTitleAt(2, "Tab 2"); } }); final RTabbedPane rtp = new RTabbedPane(tabbedPane, null, null, new LoggingRecorder()); final Object[] content = new Object[] { null }; siw(new Runnable() { @Override public void run() { content[0] = rtp.getContent(); } }); JSONArray a = new JSONArray(content[0]); Assert.assertEquals("[[\"Tab 1\",\"Tab 2\",\"Tab 2(1)\",\"Tab 4\"]]", a.toString()); }
private void verifyMetrics(JSONObject telemetry) { JSONArray metrics = telemetry.getJSONArray(METRICS); assertEquals(2, metrics.length()); Map<String, JSONObject> parsedMetrics = new HashMap<>(); for (Object obj : metrics) { JSONObject metric = (JSONObject) obj; parsedMetrics.put(metric.getString(NAME), metric); } assertEquals(2, parsedMetrics.size()); JSONObject connectionMetric = parsedMetrics.get(CONNECTION_METRIC); JSONObject microphoneMetric = parsedMetrics.get(MICROPHONE_METRIC); assertNotNull(connectionMetric); assertNotNull(microphoneMetric); assertNotNull(connectionMetric.getString(START)); assertNotNull(microphoneMetric.getString(START)); assertNotNull(connectionMetric.getString(END)); assertNotNull(microphoneMetric.getString(END)); }
private void getAppRecommends() { showLoading(); OneApi.getAndroidRecommends(this.activity, new JsonCallback(this.activity) { public void ok(String response) { super.ok(response); try { JSONArray recommends = new JSONObject(response).getJSONArray ("android_recommends"); AppRecommendActivity.this.apps = AppRecommend.parseAppRecommends(recommends .toString()); AppRecommendActivity.this.initAppRecommendView(); } catch (JSONException e) { e.printStackTrace(); } } public void onFinish() { super.onFinish(); AppRecommendActivity.this.dismissLoading(); } }); }
@Test public void parseJson_should_return_correct_testclass_object() throws StockException { String jsonString = "{ \"id\":1234, \"description\":\"Sample description\", \"property\": { \"key\": \"test key\" }, \"array\":[3,5,9,10], \"required\":true, \"precision\":10.12}"; JSONObject testObj = new JSONObject(jsonString); TestClass parsedObj = (TestClass) JsonUtils.parseJson(TestClass.class, jsonString); Assert.assertEquals(testObj.opt("id"), checkNull(parsedObj.getId())); Assert.assertEquals(testObj.opt("description"), checkNull(parsedObj.getDescription())); Assert.assertEquals(testObj.opt("required"), checkNull(parsedObj.getRequired())); if (!testObj.isNull("array")) { JSONArray objArray = (JSONArray) testObj.opt("array"); ArrayList<Integer> parsedArray = parsedObj.getArray(); for (int i = 0; i < objArray.length(); i++) { Assert.assertTrue(parsedArray.contains(objArray.get(i))); } } if (!testObj.isNull("property")) { JSONObject obj = (JSONObject) testObj.opt("property"); Assert.assertNotNull(parsedObj.getProperty()); Assert.assertEquals(checkNull(obj.opt("key")), parsedObj.getProperty().getKey()); } }
@NonNull private List<PaymentMethod> parsePreferredPaymentMethods(final JSONArray jsonArray) throws JSONException { final List<PaymentMethod> paymentMethodList = new ArrayList<>(); if (jsonArray == null) { return paymentMethodList; } for (int i = 0; i < jsonArray.length(); i++) { paymentMethodList.add(PaymentMethod.createPaymentMethod(jsonArray.getJSONObject(i), getLogoBaseURL(), true)); } return paymentMethodList; }
public static GeoOri parse(JSONObject object) { GeoOri geoOri = null; if (object != null) { geoOri = new GeoOri(); geoOri.type = object.optString("type"); JSONArray array = object.optJSONArray("coordinates"); geoOri.latitude = array.optDouble(0); geoOri.longitude = array.optDouble(1); } return geoOri; }
public void loadSavedServer(String module) { disabledlist.get(module).clear(); if (DRIVER.hasKey(DRIVER.CONFIG, module+"_disabled_servers")) { JSONArray jArray = Utils.objectToJSONArray(DRIVER.getPropertyOnly(DRIVER.CONFIG, module + "_disabled_servers")); if (jArray != null) { for (int i = 0; i < jArray.length(); i++) { disabledlist.get(module).add(jArray.get(i).toString()); Console.debug("Load: |" + module + " " + jArray.get(i).toString()); } } } Console.debug("Disabled Servers: "+module+" |"+ disabledlist.get(module).size()); }
/** * Converts the specified {@link Collection collection} to a * {@link JSONArray JSON array}. * * @param <T> * the type of elements maintained by the specified collection * @param collection * the specified collection * @return a {@link JSONArray JSON array} */ public static <T> JSONArray toJSONArray(final Collection<T> collection) { final JSONArray ret = new JSONArray(); if (null == collection) { return ret; } for (final T object : collection) { ret.put(object); } return ret; }
public static JSONArray toJSON(MultiPolygon multiPoly) { int size = multiPoly.getNumGeometries(); JSONArray coords = new JSONArray(size); for (int i = 0; i < size; i++) { Polygon poly = (Polygon)multiPoly.getGeometryN(i); coords.put(toJSON(poly)); } return coords; }
public void onPictureTaken(String originalPicture) { Log.d(TAG, "returning pictures"); JSONArray data = new JSONArray(); data.put(originalPicture); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data); pluginResult.setKeepCallback(true); takePictureCallbackContext.sendPluginResult(pluginResult); }
/** * Send the transactions that are not valid to all the relays. * * @param block */ private void sendNotValidTransactions(final Block block) { final HashSet<Transaction> allBadTransactions = bcManager.getBlockChain().getBadTransactions(block); if(allBadTransactions.isEmpty()) return; final JSONArray badTransactions = new JSONArray(); for(final Transaction badTransaction : allBadTransactions) { badTransactions.put(badTransaction.toJSON()); } final JSONObject option = new JSONObject(); option.put("transactions", badTransactions); final Message transactionsNotValid = new Message(Message.TRANSACTIONS_NOT_VALID, option); sendToAll(transactionsNotValid); }
@Test public void shouldGetRecords() throws IOException, JSONException { Records records; try (InputStream stream = getResource("podcasts/podcast-1.html")) { PodcastLayoutContent content = parser.parse(0, stream, "UTF-8", RESPONSE_URL); records = content.getRecords(); } try (InputStream resource = getResource("podcasts/podcast-1.records.json")) { String json = IOUtils.toString(resource, "UTF-8"); assertEquals(new JSONArray(json), records.toJson()); } }
public IGuildChannel buildGuildChannel (IGuild guild, JSONObject json) { handleBuildError(json); guild = json.has("guild_id") ? identity.getGuild(json.getString("guild_id")) : guild; String id = json.getString("id"); String name = json.getString("name"); int position = json.getInt("position"); IChannel.Type type = IChannel.Type.getByKey(json.getInt("type")); /* Build PermOverwrite Objects */ List<PermOverwrite> overwrites = new ArrayList<>(); JSONArray perms = json.getJSONArray("permission_overwrites"); for (int i = 0; i < perms.length(); i++) { overwrites.add(buildPermOverwrite(guild, perms.getJSONObject(i))); } if (type.equals(IChannel.Type.GUILD_TEXT)) { String topic = json.isNull("topic") ? null : json.getString("topic"); return new TextChannel(identity, guild, id) .setName(name) .setPosition(position) .setTopic(topic) .setPermOverwrites(overwrites); } else { int bitrate = json.getInt("bitrate"); int userLimit = json.getInt("user_limit"); return new VoiceChannel(identity, guild, id) .setName(name) .setBitrate(bitrate) .setUserLimit(userLimit) .setPermOverwrites(overwrites); } }
public List<Download> getDownloads() { List<Download> list = new ArrayList<>(); try { JSONArray downloads = mKernel.getJSONArray("downloads"); for (int i = 0; i < downloads.length(); i++) { list.add(new Download(downloads.getJSONObject(i))); } } catch (JSONException e) { e.printStackTrace(); } return list; }
/** * Convert the specified complex JSON object to the respective Java types using the specified * object type that has the actual type definition. * * @param jObject the JSON object * @param type the object type to be used for conversion * @return the respective Java object representation using the specified type * @throws JSONException */ public static Object jsonToObject(final Object jObject, final DataType type) throws JSONException { if (jObject == null || jObject == JSONObject.NULL) { return null; } /** convert from JSON-string to the respective Java object **/ if (type instanceof WrapperType) { return jsonToObject(jObject, ((WrapperType) type).getBasicObjectType()); } else if (type instanceof BasicTypes) { if (BasicTypes.BINARY.equals(type)) { return toArray(BINARY_TYPE, (JSONArray) jObject); } else { final Function<String, Object> function = STRING_TO_TYPE_CONVERT_MAP.get(type); if (function == null) { throw new IllegalArgumentException("Unsupported type: " + type.toString()); } return function.apply((String) jObject); } } else if (type instanceof ListType) { return toArray((ListType) type, (JSONArray) jObject); } else if (type instanceof MapType) { return toMap((MapType) type, (JSONObject) jObject); } else if (type instanceof StructType) { return toStruct((StructType) type, (JSONArray) jObject); } else if (type instanceof UnionType) { return toUnion((UnionType) type, (JSONArray) jObject); } else { throw new IllegalArgumentException("Unsupported type: " + type.toString()); } }