org.json.JSONException Java Examples
The following examples show how to use
org.json.JSONException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WvWebView.java From YCWebView with Apache License 2.0 | 7 votes |
private JSONObject messageToJsonObject(WvMessage message) { JSONObject jo = new JSONObject(); try { if (message.callbackId != null) { jo.put(CALLBACK_ID_STR, message.callbackId); } if (message.data != null) { jo.put(DATA_STR, message.data); } if (message.handlerName != null) { jo.put(HANDLER_NAME_STR, message.handlerName); } if (message.responseId != null) { jo.put(RESPONSE_ID_STR, message.responseId); } if (message.responseData != null) { jo.put(RESPONSE_DATA_STR, message.responseData); } } catch (JSONException e) { e.printStackTrace(); } return jo; }
Example #2
Source File: GiftBeanParser.java From letv with Apache License 2.0 | 6 votes |
public GiftBean parser(String jsonString) { LogInfo.log("GiftBeanParser", "GiftBeanParser + GiftBeanString =" + jsonString); GiftBean giftBean = new GiftBean(); if (!TextUtils.isEmpty(jsonString)) { try { JSONObject json = new JSONObject(jsonString); giftBean.is_first = json.optBoolean("is_first", true); giftBean.big_type = json.optInt("big_type"); giftBean.title = json.optString("title"); giftBean.price_image = json.optString("price_image"); giftBean.company_name = json.optString("company_name"); } catch (JSONException e) { LogInfo.log("GiftBeanParser", "jsonString error"); e.printStackTrace(); } } LogInfo.log("GiftBeanParser", "parser + GiftBean =" + giftBean.toString()); return giftBean; }
Example #3
Source File: OpenAPIParser.java From DeviceConnect-Android with MIT License | 6 votes |
/** * 応答用定義の解析を行います. * * @param jsonObject 応答用定義が格納されたJSONオブジェクト * @return 応答用定義 * @throws JSONException JSONの解析に失敗した場合に発生 */ private static Response parseResponse(JSONObject jsonObject) throws JSONException { Response response = new Response(); for (Iterator<String> it = jsonObject.keys(); it.hasNext();) { String key = it.next(); Object object = jsonObject.get(key); if (object != null) { if ("description".equalsIgnoreCase(key)) { response.setDescription((String) object); } else if ("schema".equalsIgnoreCase(key)) { response.setSchema(parseSchema((JSONObject) object)); } else if ("headers".equalsIgnoreCase(key)) { response.setHeaders(parseHeaders((JSONObject) object)); } else if ("examples".equalsIgnoreCase(key)) { response.setExamples(parseExamples((JSONObject) object)); } else if (key.startsWith("x-")) { response.addVendorExtension(key, parseVendorExtension(object)); } } } return response; }
Example #4
Source File: MediaSerializer.java From KlyphMessenger with MIT License | 6 votes |
@Override public JSONObject serializeObject(GraphObject object) { JSONObject json = new JSONObject(); serializePrimitives(object, json); Media media = (Media) object; PhotoSerializer ps = new PhotoSerializer(); VideoSerializer vs = new VideoSerializer(); SwfSerializer swfs = new SwfSerializer(); try { json.put("photo", ps.serializeObject(media.getPhoto())); json.put("video", vs.serializeObject(media.getVideo())); json.put("swf", swfs.serializeObject(media.getSwf())); } catch (JSONException e) { Log.d("MediaSerializer", "JsonException " + e); } return json; }
Example #5
Source File: WebTrace.java From ArgusAPM with Apache License 2.0 | 6 votes |
public static void dispatch(JSONObject jsonObject) { if (!Manager.getInstance().getTaskManager().taskIsCanWork(ApmTask.TASK_WEBVIEW)) { if (Env.DEBUG) { LogX.d(Env.TAG, SUB_TAG, "webview task is not work"); } return; } ITask task = Manager.getInstance().getTaskManager().getTask(ApmTask.TASK_WEBVIEW); if (task != null && jsonObject != null) { try { WebInfo webInfo = new WebInfo(); webInfo.url = jsonObject.getString(WebInfo.DBKey.KEY_URL); webInfo.isWifi = SystemUtils.isWifiConnected(); webInfo.navigationStart = jsonObject.getLong(WebInfo.DBKey.KEY_NAVIGATION_START); webInfo.responseStart = jsonObject.getLong(WebInfo.DBKey.KEY_RESPONSE_START); webInfo.pageTime = jsonObject.getLong(WebInfo.DBKey.KEY_PAGE_TIME); task.save(webInfo); } catch (JSONException e) { e.printStackTrace(); } } }
Example #6
Source File: MainActivity.java From SocketIO_Chat_APP with MIT License | 6 votes |
public void sendMessage(View view){ Log.i(TAG, "sendMessage: "); String message = textField.getText().toString().trim(); if(TextUtils.isEmpty(message)){ Log.i(TAG, "sendMessage:2 "); return; } textField.setText(""); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("message", message); jsonObject.put("username", Username); jsonObject.put("uniqueId", uniqueId); } catch (JSONException e) { e.printStackTrace(); } Log.i(TAG, "sendMessage: 1"+ mSocket.emit("chat message", jsonObject)); }
Example #7
Source File: InstanceRegisteredEventMixinTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void verifyDeserializeWithOnlyRequiredProperties() throws JSONException, JsonProcessingException { String json = new JSONObject().put("instance", "test123").put("timestamp", 1587751031.000000000) .put("type", "REGISTERED") .put("registration", new JSONObject().put("name", "test").put("healthUrl", "http://localhost:9080/heath")) .toString(); InstanceRegisteredEvent event = objectMapper.readValue(json, InstanceRegisteredEvent.class); assertThat(event).isNotNull(); assertThat(event.getInstance()).isEqualTo(InstanceId.of("test123")); assertThat(event.getVersion()).isEqualTo(0L); assertThat(event.getTimestamp()).isEqualTo(Instant.ofEpochSecond(1587751031).truncatedTo(ChronoUnit.SECONDS)); Registration registration = event.getRegistration(); assertThat(registration).isNotNull(); assertThat(registration.getName()).isEqualTo("test"); assertThat(registration.getManagementUrl()).isNull(); assertThat(registration.getHealthUrl()).isEqualTo("http://localhost:9080/heath"); assertThat(registration.getServiceUrl()).isNull(); assertThat(registration.getSource()).isNull(); assertThat(registration.getMetadata()).isEmpty(); }
Example #8
Source File: TestUtils.java From ambry with Apache License 2.0 | 6 votes |
protected JSONArray getDatacenters(boolean createNew) throws JSONException { List<String> names = new ArrayList<String>(datacenterCount); if (createNew) { datanodeJSONArrays = new ArrayList<JSONArray>(datacenterCount); } int curBasePort = basePort; int sslPort = curBasePort + 10000; int http2Port = sslPort + 10000; for (int i = 0; i < datacenterCount; i++) { names.add(i, "DC" + i); if (createNew) { datanodeJSONArrays.add(i, getDataNodes(curBasePort, sslPort, http2Port, getDisks())); } else { updateDataNodeJsonArray(datanodeJSONArrays.get(i), curBasePort, sslPort, http2Port, getDisks()); } curBasePort += dataNodeCount; } basePort += dataNodeCount; return TestUtils.getJsonArrayDatacenters(names, datanodeJSONArrays); }
Example #9
Source File: ApiApp.java From hellosign-java-sdk with MIT License | 6 votes |
/** * Constructor that instantiates an ApiApp object based on the JSON response from the HelloSign * API. * * @param json JSONObject * @throws HelloSignException thrown if there is a problem parsing the JSONObject */ public ApiApp(JSONObject json) throws HelloSignException { super(json, APIAPP_KEY); owner_account = new Account(dataObj, APIAPP_OWNER_ACCOUNT); if (dataObj.has(ApiAppOauth.APIAPP_OAUTH_KEY) && !dataObj .isNull(ApiAppOauth.APIAPP_OAUTH_KEY)) { oauth = new ApiAppOauth(dataObj); } if (dataObj.has(WhiteLabelingOptions.WHITE_LABELING_OPTIONS_KEY) && !dataObj.isNull(WhiteLabelingOptions.WHITE_LABELING_OPTIONS_KEY)) { white_labeling_options = new WhiteLabelingOptions(dataObj); try { // Re-save the JSON Object back to the parent object, since // we are currently returning this as a string dataObj.put(WhiteLabelingOptions.WHITE_LABELING_OPTIONS_KEY, white_labeling_options.dataObj); } catch (JSONException e) { throw new HelloSignException("Unable to process white labeling options"); } } }
Example #10
Source File: UmbelSearchConcept.java From wandora with GNU General Public License v3.0 | 6 votes |
private ArrayList<String> getAsStringArray(Object o) throws JSONException { ArrayList<String> array = new ArrayList(); if(o != null) { if(o instanceof String) { array.add(o.toString()); } else if(o instanceof JSONArray) { JSONArray a = (JSONArray) o; for(int i=0; i<a.length(); i++) { String typeUri = a.getString(i); array.add(typeUri); } } } return array; }
Example #11
Source File: SelfDescribingJsonTest.java From snowplow-android-tracker with Apache License 2.0 | 6 votes |
public void testCreateWithSelfDescribingJsonWithMore() throws JSONException { testMap.put("a", "b"); testMap.put("c", "d"); SelfDescribingJson json = new SelfDescribingJson(testSchema, new SelfDescribingJson(testSchema, testMap)); // {"schema":"org.test.scheme","data":{"schema":"org.test.scheme","data":{"a":"b","c":"d"}}} String s = json.toString(); JSONObject map = new JSONObject(s); assertEquals(testSchema, map.getString("schema")); JSONObject innerMap = map.getJSONObject("data"); assertEquals(testSchema, innerMap.getString("schema")); JSONObject innerData = innerMap.getJSONObject("data"); assertEquals(2, innerData.length()); assertEquals("b", innerData.getString("a")); assertEquals("d", innerData.getString("c")); }
Example #12
Source File: KpiResource.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
@POST @Path("/getKpiTemplate") public String loadTemplate(@Context HttpServletRequest req) throws EMFUserError, EMFInternalError, JSONException, TransformerFactoryConfigurationError, TransformerException { ObjTemplate template; try { JSONObject request = RestUtilities.readBodyAsJSONObject(req); template = DAOFactory.getObjTemplateDAO().getBIObjectActiveTemplate(request.getInt("id")); if (template == null) { return new JSONObject().toString(); } } catch (Exception e) { logger.error("Error converting JSON Template to XML...", e); throw new SpagoBIServiceException(this.request.getPathInfo(), "An unexpected error occured while executing service", e); } return new JSONObject(Xml.xml2json(new String(template.getContent()))).toString(); }
Example #13
Source File: RouterServiceValidator.java From sdl_java_suite with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected boolean verifyVersion(int version, JSONArray versions){ if(version<0){ return false; } if(versions == null || versions.length()==0){ return true; } for(int i=0;i<versions.length();i++){ try { if(version == versions.getInt(i)){ return false; } } catch (JSONException e) { continue; } }//We didn't find our version in the black list. return true; }
Example #14
Source File: VectorLayer.java From android_maplib with GNU Lesser General Public License v3.0 | 6 votes |
public void fillFromGeoJson( Uri uri, int srs, IProgressor progressor) throws IOException, JSONException, NGException, SQLiteException { InputStream inputStream = mContext.getContentResolver().openInputStream(uri); if (inputStream == null) { throw new NGException(mContext.getString(R.string.error_download_data)); } if (null != progressor) { progressor.setMessage(mContext.getString(R.string.create_features)); } GeoJSONUtil.fillLayerFromGeoJSONStream(this, inputStream, srs, progressor); }
Example #15
Source File: GitCloneHandlerV1.java From orion.server with Eclipse Public License 1.0 | 6 votes |
public static void doConfigureClone(Git git, String user, String gitUserName, String gitUserMail) throws IOException, CoreException, JSONException { StoredConfig config = git.getRepository().getConfig(); if (gitUserName == null && gitUserMail == null) { JSONObject gitUserConfig = getUserGitConfig(user); if (gitUserConfig != null) { gitUserName = gitUserConfig.getString("GitName"); //$NON-NLS-1$ gitUserMail = gitUserConfig.getString("GitMail"); //$NON-NLS-1$ } } if (gitUserName != null) config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME, gitUserName); if (gitUserMail != null) config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL, gitUserMail); config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false); config.save(); }
Example #16
Source File: YahooStockQuoteRepository.java From ministocks with MIT License | 6 votes |
JSONArray retrieveQuotesAsJson(Cache cache, List<String> symbols) throws JSONException { String csvText = getQuotesCsv(cache, symbols); if (isDataInvalid(csvText)) { return null; } JSONArray quotes = new JSONArray(); for (String line : csvText.split("\n")) { String[] values = parseCsvLine(line); if (isCsvLineInvalid(values, symbols)) { continue; } JSONObject data = new JSONObject(); data.put("symbol", values[0]); data.put("price", values[3]); data.put("change", values[4]); data.put("percent", values[5]); data.put("exchange", values[6]); data.put("volume", values[7]); data.put("name", values[8]); quotes.put(data); } return quotes; }
Example #17
Source File: CPU.java From drmips with GNU General Public License v3.0 | 6 votes |
/** * Parses and sets the identifiers of the registers. * @param cpu The CPU to set the registers informations. * @param regs JSONArray that contains the registers. * @throws JSONException If the JSON file is malformed. * @throws InvalidCPUException If not all registers are specified or a register is invalid. */ private static void parseJSONRegNames(CPU cpu, JSONArray regs) throws JSONException, InvalidCPUException { if(regs.length() != cpu.getRegBank().getNumberOfRegisters()) throw new InvalidCPUException("Not all registers have been specified in the registers block!"); cpu.registerNames = new ArrayList<>(cpu.getRegBank().getNumberOfRegisters()); String id; for(int i = 0; i < regs.length(); i++) { id = regs.getString(i).trim().toLowerCase(); if(id.isEmpty()) throw new InvalidCPUException("Invalid name " + id + "!"); if(!id.matches(REGNAME_REGEX)) // has only letters and digits and starts with a letter? throw new InvalidCPUException("Invalid name " + id + "!"); if(cpu.hasRegister(REGISTER_PREFIX + id)) throw new InvalidCPUException("Invalid name " + id + "!"); cpu.registerNames.add(id); } }
Example #18
Source File: VideoStream.java From cordova-rtmp-rtsp-stream with Apache License 2.0 | 6 votes |
@Override public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { int i = 0; for (int r : grantResults) { if (r == PackageManager.PERMISSION_DENIED) { this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR + " Request Code: " + REQ_CODE + ", Actions: " + _action + ", Permission: " + permissions[i])); return; } i++; } if (requestCode == REQ_CODE) { this._methods(_action, _args); } }
Example #19
Source File: Directions.java From MapNavigator with Apache License 2.0 | 6 votes |
private void parseDirections(){ try { JSONObject json = new JSONObject(directions); if(!json.isNull("routes")){ JSONArray route = json.getJSONArray("routes"); for(int k=0;k<route.length(); k++){ JSONObject obj3 = route.getJSONObject(k); routes.add(new Route(obj3)); } } } catch (JSONException e) { e.printStackTrace(); } }
Example #20
Source File: Tencent.java From YiBo with Apache License 2.0 | 6 votes |
@Override public Status createFavorite(String statusId) throws LibException { if (StringUtil.isEmpty(statusId)) { throw new LibException(LibResultCode.E_PARAM_NULL); } try { HttpRequestWrapper httpRequestWrapper = new HttpRequestWrapper(HttpMethod.POST, conf.getCreateFavoriteUrl(), auth); httpRequestWrapper.addParameter("id", statusId); httpRequestWrapper.addParameter("format", RESPONSE_FORMAT); String response = HttpRequestHelper.execute(httpRequestWrapper, responseHandler); JSONObject json = new JSONObject(response); Status status = new Status(); status.setStatusId(ParseUtil.getRawString("id", json)); status.setServiceProvider(ServiceProvider.Tencent); return status; } catch (JSONException e) { throw new LibException(LibResultCode.JSON_PARSE_ERROR, e); } }
Example #21
Source File: JsonUtil.java From AppAuth-Android with Apache License 2.0 | 6 votes |
public static <T> List<T> get(JSONObject json, ListField<T> field) { try { if (!json.has(field.key)) { return field.defaultValue; } Object value = json.get(field.key); if (!(value instanceof JSONArray)) { throw new IllegalStateException(field.key + " does not contain the expected JSON array"); } JSONArray arrayValue = (JSONArray) value; ArrayList<T> values = new ArrayList<>(); for (int i = 0; i < arrayValue.length(); i++) { values.add(field.convert(arrayValue.getString(i))); } return values; } catch (JSONException e) { // all appropriate steps are taken above to avoid a JSONException. If it is still // thrown, indicating an implementation change, throw an excpetion throw new IllegalStateException("unexpected JSONException", e); } }
Example #22
Source File: NewActivity.java From StreamHub-Android-SDK with MIT License | 6 votes |
@Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); dismissProgressDialog(); try { if (!errorResponse.isNull("msg")) { showAlert(errorResponse.getString("msg"), "TRY AGAIN", tryAgain); } else { showAlert("Something went wrong.", "TRY AGAIN", tryAgain); } } catch (JSONException e) { e.printStackTrace(); showAlert("Something went wrong.", "TRY AGAIN", tryAgain); } }
Example #23
Source File: EditCameraLocationActivity.java From evercam-android with GNU Affero General Public License v3.0 | 5 votes |
protected void onPostExecute(HttpResponse<JsonNode> response) { String jsonString = response.getBody().toString(); try { JSONObject jsonobj = new JSONObject(jsonString); timeZone = jsonobj.getString("timeZoneId"); // cameraToUpdate.setTimezone(timeZone); // cameraToUpdate.setLatitude(tappedLatLng.latitude); // cameraToUpdate.setLongitude(tappedLatLng.longitude); Log.v("Time Zone", timeZone); } catch (JSONException e) { e.printStackTrace(); } }
Example #24
Source File: OpenAPIParser.java From DeviceConnect-Android with MIT License | 5 votes |
/** * API 全体で使用できるセキュリティの定義を解析します. * * @param jsonObject API 全体で使用できるセキュリティの定義を格納したオブジェクト * @return API 全体で使用できるセキュリティの定義 * @throws JSONException JSONの解析に失敗した場合に発生 */ private static Map<String, SecurityScheme> parseSecurityDefinitions(JSONObject jsonObject) throws JSONException { Map<String, SecurityScheme> securityScheme = new HashMap<>(); for (Iterator<String> it = jsonObject.keys(); it.hasNext();) { String key = it.next(); Object object = jsonObject.get(key); if (object instanceof JSONObject) { securityScheme.put(key, parseSecurityScheme((JSONObject) object)); } } return securityScheme; }
Example #25
Source File: Util.java From HypFacebook with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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. * * @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 */ @Deprecated 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; }
Example #26
Source File: VoIPServerConfig.java From Telegram with GNU General Public License v2.0 | 5 votes |
public static void setConfig(String json){ try{ config=new JSONObject(json); nativeSetConfig(json); }catch(JSONException x){ if (BuildVars.LOGS_ENABLED) { FileLog.e("Error parsing VoIP config", x); } } }
Example #27
Source File: Route.java From hoko-android with Apache License 2.0 | 5 votes |
/** * Converts all the Route information into a JSONObject to be sent to the Hoko backend * service. * * @return The JSONObject representation of Route. */ public JSONObject getJSON(Context context) { try { JSONObject root = new JSONObject(); JSONObject route = new JSONObject(); route.put("build", App.getVersionCode(context)); route.put("device", Device.getVendor() + " " + Device.getModel()); route.put("path", mRoute); route.put("version", App.getVersion(context)); root.put("route", route); return root; } catch (JSONException e) { return new JSONObject(); } }
Example #28
Source File: Snapserver.java From snapdroid with GNU General Public License v3.0 | 5 votes |
@Override public JSONObject toJson() { JSONObject json = super.toJson(); try { json.put("controlProtocolVersion", controlProtocolVersion); } catch (JSONException e) { e.printStackTrace(); } return json; }
Example #29
Source File: ActionSheet.java From ultimate-cordova-webview-app with MIT License | 5 votes |
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (ACTION_SHOW.equals(action)) { JSONObject options = args.optJSONObject(0); String title = options.optString("title"); String subtitle = options.optString("subtitle"); int theme = options.optInt("androidTheme", 1); JSONArray buttons = options.optJSONArray("buttonLabels"); boolean androidEnableCancelButton = options.optBoolean("androidEnableCancelButton", false); boolean destructiveButtonLast = options.optBoolean("destructiveButtonLast", false); String addCancelButtonWithLabel = options.optString("addCancelButtonWithLabel"); String addDestructiveButtonWithLabel = options.optString("addDestructiveButtonWithLabel"); this.show(title, subtitle, buttons, addCancelButtonWithLabel, androidEnableCancelButton, addDestructiveButtonWithLabel, destructiveButtonLast, theme, callbackContext); // need to return as this call is async. return true; } else if (ACTION_HIDE.equals(action)) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, -1)); } return true; } return false; }
Example #30
Source File: RenRenNoteAdapter.java From YiBo with Apache License 2.0 | 5 votes |
public static Note createNote(String jsonString) throws LibException { try { JSONObject json = new JSONObject(jsonString); return createNote(json); } catch (JSONException e) { throw new LibException(LibResultCode.JSON_PARSE_ERROR, e); } }