org.json.JSONObject Java Examples
The following examples show how to use
org.json.JSONObject.
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: MarketsRespone.java From RipplePower with Apache License 2.0 | 7 votes |
public void from(Object obj) { if (obj != null) { if (obj instanceof JSONObject) { JSONObject result = (JSONObject) obj; this.rowkey = result.optString("rowkey"); this.count = result.optLong("count"); this.startTime = result.optString("startTime"); this.endTime = result.optString("endTime"); this.exchange.copyFrom(result.opt("exchange")); this.exchangeRate = result.optDouble("exchangeRate"); this.total = result.optDouble("total"); JSONArray arrays = result.optJSONArray("components"); if (arrays != null) { int size = arrays.length(); for (int i = 0; i < size; i++) { MarketComponent marketComponent = new MarketComponent(); marketComponent.from(arrays.getJSONObject(i)); components.add(marketComponent); } } } } }
Example #2
Source File: ElectrumNotifier.java From jelectrum with MIT License | 6 votes |
public void sendAddressHistory(StratumConnection conn, Object request_id, ByteString scripthash, boolean include_confirmed, boolean include_mempool) { Subscriber sub = new Subscriber(conn, request_id); try { JSONObject reply = sub.startReply(); reply.put("result", getScriptHashHistory(scripthash,include_confirmed,include_mempool)); sub.sendReply(reply); } catch(org.json.JSONException e) { throw new RuntimeException(e); } }
Example #3
Source File: FileUtils.java From keemob with MIT License | 6 votes |
private boolean needPermission(String nativeURL, int permissionType) throws JSONException { JSONObject j = requestAllPaths(); ArrayList<String> allowedStorageDirectories = new ArrayList<String>(); allowedStorageDirectories.add(j.getString("applicationDirectory")); allowedStorageDirectories.add(j.getString("applicationStorageDirectory")); if(j.has("externalApplicationStorageDirectory")) { allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory")); } if(permissionType == READ && hasReadPermission()) { return false; } else if(permissionType == WRITE && hasWritePermission()) { return false; } // Permission required if the native url lies outside the allowed storage directories for(String directory : allowedStorageDirectories) { if(nativeURL.startsWith(directory)) { return false; } } return true; }
Example #4
Source File: ForwardList.java From ki4a with Apache License 2.0 | 6 votes |
protected static List<ForwardInfo> loadForwardInfo(Context context) { List<ForwardInfo> arrayList = new ArrayList<>(); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); String jsonString = settings.getString("port_forward_json", ""); if(jsonString.isEmpty()) return arrayList; try { JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject obj = jsonArray.getJSONObject(i); arrayList.add(ForwardInfo.getForwardInfo(obj)); } } catch (JSONException e) { e.printStackTrace(); } return arrayList; }
Example #5
Source File: ExampleInstrumentedTest.java From XmlToJson with Apache License 2.0 | 6 votes |
@Test public void attributeReplacementTest() throws Exception { Context context = InstrumentationRegistry.getTargetContext(); AssetManager assetManager = context.getAssets(); InputStream inputStream = assetManager.open("common.xml"); XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null) .setAttributeName("/library/book/id", "attributeReplacement") .build(); inputStream.close(); JSONObject result = xmlToJson.toJson(); JSONObject library = result.getJSONObject("library"); JSONArray books = library.getJSONArray("book"); assertEquals(books.length(), 2); for (int i = 0; i < books.length(); ++i) { JSONObject book = books.getJSONObject(i); book.getInt("attributeReplacement"); } }
Example #6
Source File: PassportScopeElementOne.java From TGPassportAndroidSDK with MIT License | 6 votes |
@Override Object toJSON(){ if(!selfie && !translation && !nativeNames) return type; try{ JSONObject o=new JSONObject(); o.put("type", type); if(selfie) o.put("selfie", true); if(translation) o.put("translation", true); if(nativeNames) o.put("native_names", true); return o; }catch(JSONException ignore){} return null; }
Example #7
Source File: InterstitialExecutor.java From cordova-plugin-admob-free with MIT License | 6 votes |
public PluginResult requestAd(JSONObject options, CallbackContext callbackContext) { CordovaInterface cordova = plugin.cordova; plugin.config.setInterstitialOptions(options); if (interstitialAd == null) { callbackContext.error("interstitialAd is null, call createInterstitialView first"); return null; } final CallbackContext delayCallback = callbackContext; cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (interstitialAd == null) { return; } interstitialAd.loadAd(plugin.buildAdRequest()); delayCallback.success(); } }); return null; }
Example #8
Source File: JsonRPC.java From snapdroid with GNU General Public License v3.0 | 6 votes |
JSONObject toJson() { JSONObject response = new JSONObject(); try { response.put("jsonrpc", "2.0"); if (error != null) response.put("error", error); else if (result != null) response.put("result", result); else throw new JSONException("error and result are null"); response.put("id", id); return response; } catch (JSONException e) { e.printStackTrace(); return null; } }
Example #9
Source File: AipImageClassify.java From java-sdk with Apache License 2.0 | 6 votes |
/** * logo商标识别—添加接口 * 使用入库接口请先在[控制台](https://console.bce.baidu.com/ai/#/ai/imagerecognition/overview/index)创建应用并申请建库,建库成功后方可正常使用。 * * @param image - 二进制图像数据 * @param brief - brief,检索时带回。此处要传对应的name与code字段,name长度小于100B,code长度小于150B * @param options - 可选参数对象,key: value都为string类型 * options - options列表: * @return JSONObject */ public JSONObject logoAdd(byte[] image, String brief, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); String base64Content = Base64Util.encode(image); request.addBody("image", base64Content); request.addBody("brief", brief); if (options != null) { request.addBody(options); } request.setUri(ImageClassifyConsts.LOGO_ADD); postOperation(request); return requestServer(request); }
Example #10
Source File: GraphObjectAdapter.java From android-skeleton-project with MIT License | 6 votes |
protected URI getPictureUriOfGraphObject(T graphObject) { String uri = null; Object o = graphObject.getProperty(PICTURE); if (o instanceof String) { uri = (String) o; } else if (o instanceof JSONObject) { ItemPicture itemPicture = GraphObject.Factory.create((JSONObject) o).cast(ItemPicture.class); ItemPictureData data = itemPicture.getData(); if (data != null) { uri = data.getUrl(); } } if (uri != null) { try { return new URI(uri); } catch (URISyntaxException e) { } } return null; }
Example #11
Source File: WebScriptUtil.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 6 votes |
public static Date getDate(JSONObject json) throws ParseException { if(json == null) { return null; } String dateTime = json.optString(DATE_TIME); if(dateTime == null) { return null; } String format = json.optString(FORMAT); if(format!= null && ISO8601.equals(format) == false) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.parse(dateTime); } return ISO8601DateFormat.parse(dateTime); }
Example #12
Source File: StringSchemaTest.java From json-schema with Apache License 2.0 | 5 votes |
@Test public void toStringWithNullableTrueTest() { JSONObject rawSchemaJson = ResourceLoader.DEFAULT.readObj("tostring/stringschema.json"); rawSchemaJson.put("nullable", true); String actual = loadWithNullableSupport(rawSchemaJson).toString(); assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson)); }
Example #13
Source File: Utility.java From coolweather with Apache License 2.0 | 5 votes |
/** * 将返回的JSON数据解析成Weather实体类 */ public static Weather handleWeatherResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather"); String weatherContent = jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent, Weather.class); } catch (Exception e) { e.printStackTrace(); } return null; }
Example #14
Source File: MultiServerStatus.java From orion.server with Eclipse Public License 1.0 | 5 votes |
@Override public JSONObject toJSON() { if (!statuses.isEmpty()) return getLastStatus().toJSON(); else return super.toJSON(); }
Example #15
Source File: Forum.java From android-discourse with Apache License 2.0 | 5 votes |
@Override public void load(JSONObject object) throws JSONException { super.load(object); name = getString(object, "name"); JSONObject topic = object.getJSONArray("topics").getJSONObject(0); numberOfOpenSuggestions = topic.getInt("open_suggestions_count"); numberOfVotesAllowed = topic.getInt("votes_allowed"); categories = deserializeList(topic, "categories", Category.class); if (categories == null) categories = new ArrayList<Category>(); }
Example #16
Source File: JSONSchemaValidationTest.java From nakadi with MIT License | 5 votes |
@Test public void validationOfBusinessEventShouldAllowSpanCtxtInMetadata() { final EventType et = EventTypeTestBuilder.builder().name("some-event-type") .schema(basicSchema()).compatibilityMode(CompatibilityMode.COMPATIBLE).build(); et.setCategory(EventCategory.BUSINESS); final JSONObject validEvent = new JSONObject("{\"metadata\":{" + "\"occurred_at\":\"1992-08-03T10:00:00Z\"," + "\"eid\":\"329ed3d2-8366-11e8-adc0-fa7ae01bbebc\"," + "\"span_ctx\": {" + " \"ot-tracer-spanid\": \"b268f901d5f2b865\"," + " \"ot-tracer-traceid\": \"e9435c17dabe8238\"," + " \"ot-baggage-foo\": \"bar\"" + "}}," + "\"foo\": \"bar\"}"); final Optional<ValidationError> noError = eventValidatorBuilder.build(et).validate(validEvent); Assert.assertThat(noError, IsOptional.isAbsent()); final JSONObject invalidEvent = new JSONObject("{\"metadata\":{" + "\"occurred_at\":\"1992-08-03T10:00:00Z\"," + "\"eid\":\"329ed3d2-8366-11e8-adc0-fa7ae01bbebc\"," + "\"span_ctx\": {" + " \"ot-tracer-spanid\": 42," + " \"ot-tracer-traceid\": \"e9435c17dabe8238\"," + " \"ot-baggage-foo\": \"bar\"" + "}}," + "\"foo\": \"bar\"}"); final Optional<ValidationError> error = eventValidatorBuilder.build(et).validate(invalidEvent); Assert.assertThat(error.get().getMessage(), CoreMatchers.equalTo("#/metadata/span_ctx/ot-tracer-spanid: expected type: String, found: Integer")); }
Example #17
Source File: Pagelet.java From mdw with Apache License 2.0 | 5 votes |
public static final Map<String,String> getMap(JSONObject jsonObj) throws JSONException { Map<String,String> map = new HashMap<String,String>(); String[] names = JSONObject.getNames(jsonObj); if (names != null) { for (String name : names) map.put(name, jsonObj.getString(name)); } return map; }
Example #18
Source File: LockedGame.java From codenjoy with GNU General Public License v3.0 | 5 votes |
@Override public void loadSave(JSONObject save) { lock.writeLock().lock(); try { game.loadSave(save); } finally { lock.writeLock().unlock(); } }
Example #19
Source File: VpnConfigGenerator.java From bitmask_android with GNU General Public License v3.0 | 5 votes |
private Obfs4Options getObfs4Options() throws JSONException { JSONObject transportOptions = obfs4Transport.getJSONObject(OPTIONS); String iatMode = transportOptions.getString("iatMode"); String cert = transportOptions.getString("cert"); String port = obfs4Transport.getJSONArray(PORTS).getString(0); String ip = gateway.getString(IP_ADDRESS); return new Obfs4Options(ip, port, cert, iatMode); }
Example #20
Source File: CommentDeserializer.java From KlyphMessenger with MIT License | 5 votes |
@Override public GraphObject deserializeObject(JSONObject data) { Target target = new Target(); deserializePrimitives(target, data); return target; }
Example #21
Source File: WSRecorder.java From marathonv5 with Apache License 2.0 | 5 votes |
@Override public void recordFileChooser(String state) { JSONObject event = new JSONObject(); event.put("type", "select_file_chooser"); event.put("value", state); JSONObject o = new JSONObject(); o.put("event", event); sendRecordMessage(o); }
Example #22
Source File: FullUpdateHandler.java From tinker-manager with Apache License 2.0 | 5 votes |
/** * 处理app更新 * @param context * @param obj */ public void handleFullUpdate(Context context, JSONObject obj) { // { // "latestVersion": "4.0.0", // "needUpdate": true, // "downloadUrl": "http://static.tianxi66.cn/app-release-360-4.0.0.apk", // "description": "赶紧下载新版本", // "forceUpdate": true, // "title": "我是标题", // "lowestSupportVersion": "2.0.0", // "updatedAt": "2017-06-30 10:42:06" // } if (obj == null) { return; } Log.d(TAG,"handlerFullUpdate: " + obj.toString()); if (obj.optBoolean("needUpdate",false)) { Intent intent = new Intent(context, FullUpdateActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("latestVersion", obj.optString("latestVersion")); intent.putExtra("needUpdate", obj.optBoolean("needUpdate", false)); intent.putExtra("downloadUrl", obj.optString("downloadUrl")); intent.putExtra("title", obj.optString("title")); intent.putExtra("description", obj.optString("description")); intent.putExtra("forceUpdate", obj.optBoolean("forceUpdate", false)); intent.putExtra("lowestSupportVersion", obj.optString("lowestSupportVersion")); intent.putExtra("updatedAt", obj.optString("updatedAt")); context.startActivity(intent); } }
Example #23
Source File: DataNode.java From ambry with Apache License 2.0 | 5 votes |
DataNode(Datacenter datacenter, JSONObject jsonObject, ClusterMapConfig clusterMapConfig) throws JSONException { logger.trace("DataNode {}", jsonObject); this.datacenter = datacenter; this.clusterMapConfig = clusterMapConfig; this.sslEnabledDataCenters = Utils.splitString(clusterMapConfig.clusterMapSslEnabledDatacenters, ","); this.hostname = clusterMapConfig.clusterMapResolveHostnames ? getFullyQualifiedDomainName(jsonObject.getString("hostname")) : jsonObject.getString("hostname"); this.portNum = jsonObject.getInt("port"); try { ResourceStatePolicyFactory resourceStatePolicyFactory = Utils.getObj(clusterMapConfig.clusterMapResourceStatePolicyFactory, this, HardwareState.valueOf(jsonObject.getString("hardwareState")), clusterMapConfig); this.dataNodeStatePolicy = resourceStatePolicyFactory.getResourceStatePolicy(); } catch (Exception e) { logger.error("Error creating resource state policy when instantiating a datanode", e); throw new IllegalStateException( "Error creating resource state policy when instantiating a datanode: " + hostname + ":" + portNum, e); } JSONArray diskJSONArray = jsonObject.getJSONArray("disks"); this.disks = new ArrayList<Disk>(diskJSONArray.length()); for (int i = 0; i < diskJSONArray.length(); ++i) { this.disks.add(new Disk(this, diskJSONArray.getJSONObject(i), clusterMapConfig)); } this.rawCapacityInBytes = calculateRawCapacityInBytes(); this.ports = new HashMap<PortType, Port>(); this.ports.put(PortType.PLAINTEXT, new Port(portNum, PortType.PLAINTEXT)); populatePorts(jsonObject); this.rackId = jsonObject.optString("rackId", null); this.xid = jsonObject.optLong("xid", ClusterMapUtils.DEFAULT_XID); validate(); }
Example #24
Source File: MusicUtils.java From AssistantBySDK with Apache License 2.0 | 5 votes |
public static boolean sendPlayLog(PlayMusic m, String userid) { if (QClient.getInstance().isSessionInvalid() && sendLoginLog() != 0) { return false; } QClient client = QClient.getInstance(); //{"command":"Music_Play_Log","userid":"kong","type":"MUSIC","musicid":"MUSIC_325771","singer":"刘德华","name":"忘情水"} Map<String, String> message = new SocketMap<String, String>(); message.put("command", "MusicPlayLog"); message.put("userid", userid); message.put("type", "ASSISTANT"); //业务类型,目前为:BBJIA或MUSIC if (m.getCloud()) message.put("musicid", m.getMusicid()); //歌曲编码,比如"MUSIC_1543"等; message.put("singer", m.getSinger()); //歌手 message.put("name", m.getTitle()); //歌曲名称 Log.i(TAG, "sendPlayLog >>>>" + message.toString()); String temp = client.sendMessage(message.toString()); Log.i(TAG, "sendPlayLog result>>>>" + temp); if (TextUtils.isEmpty(temp)) return false; try { return new JSONObject(temp).getInt("status") == 0; } catch (JSONException e) { e.printStackTrace(); } return false; }
Example #25
Source File: Globalization.java From phonegapbootcampsite with MIT License | 5 votes |
private JSONObject getFirstDayOfWeek(JSONArray options) throws GlobalizationError{ JSONObject obj = new JSONObject(); try{ int value = Calendar.getInstance(Locale.getDefault()).getFirstDayOfWeek(); //get first day of week based on user locale settings return obj.put("value", value); }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR); } }
Example #26
Source File: JsonUtil.java From AppAuth-Android with Apache License 2.0 | 5 votes |
public static void putIfNotNull( @NonNull JSONObject json, @NonNull String field, @Nullable Uri value) { checkNotNull(json, "json must not be null"); checkNotNull(field, "field must not be null"); if (value == null) { return; } try { json.put(field, value.toString()); } catch (JSONException ex) { throw new IllegalStateException("JSONException thrown in violation of contract", ex); } }
Example #27
Source File: SkuDetails.java From lantern with Apache License 2.0 | 5 votes |
public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException { mItemType = itemType; mJson = jsonSkuDetails; JSONObject o = new JSONObject(mJson); mSku = o.optString("productId"); mType = o.optString("type"); mPrice = o.optString("price"); mPriceAmountMicros = o.optLong("price_amount_micros"); mPriceCurrencyCode = o.optString("price_currency_code"); mTitle = o.optString("title"); mDescription = o.optString("description"); }
Example #28
Source File: AipOcr.java From java-sdk with Apache License 2.0 | 5 votes |
/** * 通用文字识别(高精度版)接口 * 用户向服务请求识别某张图中的所有文字,相对于通用文字识别该产品精度更高,但是识别耗时会稍长。 * * @param image - 二进制图像数据 * @param options - 可选参数对象,key: value都为string类型 * options - options列表: * detect_direction 是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:<br>- true:检测朝向;<br>- false:不检测朝向。 * probability 是否返回识别结果中每一行的置信度 * @return JSONObject */ public JSONObject basicAccurateGeneral(byte[] image, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); String base64Content = Base64Util.encode(image); request.addBody("image", base64Content); if (options != null) { request.addBody(options); } request.setUri(OcrConsts.ACCURATE_BASIC); postOperation(request); return requestServer(request); }
Example #29
Source File: Trakt.java From Mizuu with Apache License 2.0 | 5 votes |
public static boolean addMoviesToLibrary(List<Movie> movies, Context c) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); String username = settings.getString(TRAKT_USERNAME, "").trim(); String password = settings.getString(TRAKT_PASSWORD, ""); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || movies.size() == 0) return false; try { JSONObject json = new JSONObject(); json.put("username", username); json.put("password", password); JSONArray array = new JSONArray(); int count = movies.size(); for (int i = 0; i < count; i++) { JSONObject jsonMovie = new JSONObject(); jsonMovie.put("imdb_id", movies.get(i).getImdbId()); jsonMovie.put("tmdb_id", movies.get(i).getTmdbId()); jsonMovie.put("year", movies.get(i).getReleaseYear()); jsonMovie.put("title", movies.get(i).getTitle()); array.put(jsonMovie); } json.put("movies", array); Request request = MizLib.getJsonPostRequest("http://api.trakt.tv/movie/library/" + getApiKey(c), json); Response response = MizuuApplication.getOkHttpClient().newCall(request).execute(); return response.isSuccessful(); } catch (Exception e) { return false; } }
Example #30
Source File: VocabularyCapture.java From epcis with Apache License 2.0 | 5 votes |
@RequestMapping(method = RequestMethod.POST) @ResponseBody public ResponseEntity<?> post(@RequestBody String inputString, @RequestParam(required = false) Integer gcpLength) { Configuration.logger.info(" EPCIS Masterdata Document Capture Started.... "); JSONObject retMsg = new JSONObject(); if (Configuration.isCaptureVerfificationOn == true) { InputStream validateStream = CaptureUtil.getXMLDocumentInputStream(inputString); // Parsing and Validating data boolean isValidated = CaptureUtil.validate(validateStream, Configuration.wsdlPath + "/EPCglobal-epcis-masterdata-1_2.xsd"); if (isValidated == false) { return new ResponseEntity<>(new String("Error: EPCIS Masterdata Document is not validated"), HttpStatus.BAD_REQUEST); } } InputStream epcisStream = CaptureUtil.getXMLDocumentInputStream(inputString); EPCISMasterDataDocumentType epcisMasterDataDocument = JAXB.unmarshal(epcisStream, EPCISMasterDataDocumentType.class); CaptureService cs = new CaptureService(); retMsg = cs.capture(epcisMasterDataDocument, gcpLength); Configuration.logger.info(" EPCIS Masterdata Document : Captured "); if (retMsg.isNull("error") == true) return new ResponseEntity<>(retMsg.toString(), HttpStatus.OK); else return new ResponseEntity<>(retMsg.toString(), HttpStatus.BAD_REQUEST); }