/** * Remove 'null' fields from a JSONObject. This method calls itself recursively until all the * fields have been looked at. * TODO(mlamouri): move to some util class? */ private static void removeNullFields(Object object) throws JSONException { if (object instanceof JSONArray) { JSONArray array = (JSONArray) object; for (int i = 0; i < array.length(); ++i) removeNullFields(array.get(i)); } else if (object instanceof JSONObject) { JSONObject json = (JSONObject) object; JSONArray names = json.names(); if (names == null) return; for (int i = 0; i < names.length(); ++i) { String key = names.getString(i); if (json.isNull(key)) { json.remove(key); } else { removeNullFields(json.get(key)); } } } }
public static Map<String, Object> toMap(JSONObject object) { Map<String, Object> map = new HashMap<>(); String[] fields = JSONObject.getNames(object); for (String field : fields) { Object entry = object.get(field); if (entry instanceof JSONObject) { map.put(field, toMap((JSONObject) entry)); } else if (entry instanceof JSONArray) { map.put(field, toCollection((JSONArray) entry)); } else { map.put(field, entry); } } return map; }
public void handleMessage(Message msg) { super.handleMessage(msg); String smsg = msg.obj.toString(); if (msg.what == 0) { try { LEYUApplication.dev_access_token = ((JSONObject) new JSONTokener(smsg) .nextValue()).getString("access_token"); LEYUApplication.set("leyu_dev_access_token", LEYUApplication.dev_access_token); LEYUApplication.this._callback.ReturnAccessToken(LEYUApplication .dev_access_token); } catch (JSONException ex) { ex.printStackTrace(); LEYUApplication.this._callback.onFailed(ex.getMessage()); } } else if (msg.what == 1) { LEYUApplication.this._callback.OnCompleted(smsg); } else if (msg.what == 2) { LEYUApplication.this._callback.onFailed(smsg); } }
public JSONObject getPropertieSet(String propname){ if(this.target.has(propname)){ if(this.target.getJSONObject(propname).getString("type").equals("set")){ int selected = this.target.getJSONObject(propname).getInt("default"); return this.target.getJSONObject(propname).getJSONArray("sets").getJSONObject(selected); } else{ this.log.Warning("La propertie ("+propname+") especificada no corresponde al tipo llamado. Tipo declarado "+this.target.getJSONObject(propname).getString("type"), Error60.PROPERTIE_TYPE_INCORRECT); } } else { this.log.Warning("La propertie ("+propname+")especificada no existe, se envia valor null", Error60.PROPERTIE_NOT_SET); } return null; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp, String requestBody) throws IOException { _logger.debug("entering"); try { doPostHelp(req, resp, requestBody); } catch (Throwable e) { _logger.error(e.getMessage(), e); JSONObject responseBody = new ErrorJsonResponse("Unexpected exception during synthesis."); if(resp != null) resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); writeObjectToServletOutputStream(responseBody, resp); } finally { _logger.debug("exiting"); } }
public static Payload decode(String payload) throws JSONException { Builder builder = new Builder(); JSONObject json = new JSONObject(payload); builder.setDst(json.getString(KEY_DST)); builder.setSrc(json.getString(KEY_SRC)); Type type; String s = json.getString(KEY_TYPE); if(Type.EVENT.name().equalsIgnoreCase(s)) { type = Type.EVENT; } else if(Type.REPLY.name().equalsIgnoreCase(s)) { type = Type.REPLY; } else { throw new JSONException("invalid type: " + s); } builder.setType(type); builder.setId(json.getInt(KEY_ID)); try { builder.setStatus(Status.valueOf(json.optString(KEY_STATUS, "").toUpperCase())); } catch(IllegalArgumentException e) { builder.setStatus(Status.UNKNOWN); } builder.setMessage(json.getJSONObject(KEY_MESSAGE)); return builder.build(); }
void sendResult(final JSONObject payload) { Assert.notNull(payload, "Payload must not be null!"); if (!payload.has("id")) { throw new IllegalArgumentException("Payload must have an id!"); } if (Looper.myLooper() == Looper.getMainLooper()) { webView.evaluateJavascript(String.format("MEIAM.handleResponse(%s);", payload), null); } else { uiHandler.post(new Runnable() { @Override public void run() { webView.evaluateJavascript(String.format("MEIAM.handleResponse(%s);", payload), null); } }); } }
/** * Plays the item with {@code itemId} in the queue. * <p> * If {@code itemId} is not found in the queue, this method will report success without sending * a request to the receiver. * * @param itemId The ID of the item to which to jump. * @param customData Custom application-specific data to pass along with the request. May be * {@code null}. * @throws TransientNetworkDisconnectionException * @throws NoConnectionException * @throws IllegalArgumentException */ public void queueJumpToItem(int itemId, final JSONObject customData) throws TransientNetworkDisconnectionException, NoConnectionException, IllegalArgumentException { checkConnectivity(); if (itemId == MediaQueueItem.INVALID_ITEM_ID) { throw new IllegalArgumentException("itemId is not valid"); } if (mRemoteMediaPlayer == null) { LOGE(TAG, "Trying to jump in a queue with no active media session"); throw new NoConnectionException(); } mRemoteMediaPlayer .queueJumpToItem(mApiClient, itemId, customData).setResultCallback( new ResultCallback<MediaChannelResult>() { @Override public void onResult(MediaChannelResult result) { for (VideoCastConsumer consumer : mVideoConsumers) { consumer.onMediaQueueOperationResult(QUEUE_OPERATION_JUMP, result.getStatus().getStatusCode()); } } }); }
private List<Quote> getQuotes() { try { JSONArray array = new JSONArray(loadJSONFromAsset()); List<Quote> quotes = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject branchObject = array.getJSONObject(i); String quote = branchObject.getString("quote"); String author = branchObject.getString("author"); quotes.add(new Quote(author, quote)); } return quotes; } catch (JSONException e) { Log.e(TAG, "getJSONFromAsset", e); } return null; }
@Override public String write(InitializrMetadata metadata, String appUrl) { JSONObject delegate = new JSONObject(); links(delegate, metadata.getTypes().getContent(), appUrl); dependencies(delegate, metadata.getDependencies()); type(delegate, metadata.getTypes()); singleSelect(delegate, metadata.getPackagings()); singleSelect(delegate, metadata.getJavaVersions()); singleSelect(delegate, metadata.getLanguages()); singleSelect(delegate, metadata.getEdorasoneVersions()); text(delegate, metadata.getGroupId()); text(delegate, metadata.getArtifactId()); text(delegate, metadata.getVersion()); text(delegate, metadata.getName()); text(delegate, metadata.getShortName()); text(delegate, metadata.getDescription()); text(delegate, metadata.getPackageName()); return delegate.toString(); }
@Override public void process(HttpServletResponse response) throws Exception { MapMatchingRequest req = JsonMapMatchingRequestParser.parseFromRequestParams(_request); if (req == null) throw new StatusCodeException(StatusCode.BAD_REQUEST, MapMatchingErrorCodes.UNKNOWN, "MapMatchingRequest object is null."); if (MapMatchingServiceSettings.getMaximumLocations() > 0 && req.getCoordinates().length > MatrixServiceSettings.getMaximumLocations()) throw new ParameterOutOfRangeException(MapMatchingErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "sources/destinations", Integer.toString(req.getCoordinates().length), Integer.toString(MapMatchingServiceSettings.getMaximumLocations())); RouteResult result = RoutingProfileManager.getInstance().matchTrack(req); JSONObject json = null; String respFormat = _request.getParameter("format"); if (Helper.isEmpty(respFormat) || "json".equalsIgnoreCase(respFormat)) json = JsonMapMatchingResponseWriter.toJson(req, new RouteResult[] { result }); else if ("geojson".equalsIgnoreCase(respFormat)) json = JsonMapMatchingResponseWriter.toGeoJson(req, new RouteResult[] { result }); ServletUtility.write(response, json, "UTF-8"); }
@Override protected List<HashMap<String, String>> doInBackground( String... jsonData) { List<HashMap<String, String>> places = null; PlaceJSONParser placeJsonParser = new PlaceJSONParser(); try { jObject = new JSONObject(jsonData[0]); Log.v(TAG,jObject.toString()); places = placeJsonParser.parse(jObject); page_token = placeJsonParser.getPageToken(jObject); } catch (Exception e) { Log.d("Exception", e.toString()); } return places; }
public FilterRule(@NonNull JSONObject rule) throws JSONException { name = rule.getString("name"); ArrayList<String> packageNames = new ArrayList<>(); for (int i = 0; i < rule.getJSONArray("packageNames").length(); i++) { try { packageNames.add(rule.getJSONArray("packageNames").getString(i)); } catch (JSONException e) { e.printStackTrace(); } } this.packageNames = packageNames.toArray(this.packageNames); useDaytime = rule.getBoolean("useDaytime"); if (useDaytime) { from = rule.getString("from"); to = rule.getString("to"); } identityID = rule.getLong("identityID"); exec = rule.getString("exec"); }
@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 synchronized void a(b bVar) { synchronized (a.class) { if (!CommonUtils.isBlank(bVar.a())) { if (!bVar.a().equals(a())) { String str = bVar.a() + "`" + bVar.d(); if (str != null) { try { str = SecurityUtils.encrypt(SecurityUtils.getSeed(), str); JSONObject jSONObject = new JSONObject(); jSONObject.put("device", str); PublicStorage.writeDataToPublicArea("deviceid_v2", jSONObject.toString()); } catch (Exception e) { } } } } } }
/** * 解析和处理服务器返回的省级数据 */ public static boolean handleProvinceResponse(String response){ if(!TextUtils.isEmpty(response)){ try { JSONArray allProvince = new JSONArray(response); for (int i = 0; i < allProvince.length(); i++) { JSONObject object = allProvince.getJSONObject(i); Province province = new Province(); province.setProvinceName(object.getString("name")); province.setProvinceCode(object.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; }
/** * Parses the JSON returned from the Control Plane and sends the ACK to the DPN * @param body - The JSON body returned by the Control Plane in the DDN ACK */ public void ddnAck(JSONObject body){ ByteBuffer bb = ByteBuffer.allocate(14); Short dpn = DpnAPIListener.getTopicFromDpnId(new FpcDpnId((String) body.get("dpn-id"))); bb.put(toUint8(dpn)) .put(DDN_ACK); if(body.has("dl-buffering-duration")) bb.put(toUint8((short) body.getInt("dl-buffering-duration"))); if(body.has("dl-buffering-suggested-count")) bb.put(toUint16((int) body.getInt("dl-buffering-suggested-count"))); bb.put(toUint8(ZMQSBListener.getControllerTopic())) .put(toUint32(Long.parseLong(new ClientIdentifier(body.getString("client-id")).getString()))) .put(toUint32(body.getLong("op-id"))); try { sock.getBlockingQueue().put(bb); } catch (InterruptedException e) { ErrorLog.logError(e.getStackTrace()); }; }
public static Collection<Object> toCollection(JSONArray array) { Collection<Object> collection = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { Object entry = array.get(i); if (entry instanceof JSONObject) { collection.add(toMap((JSONObject) entry)); } else if (entry instanceof JSONArray) { collection.add(toCollection((JSONArray) entry)); } else { collection.add(entry); } } return collection; }
/** * Gets article permalink for adding article with the specified article. * * @param article * the specified article * @return permalink * @throws ServiceException * if invalid permalink occurs */ private String getPermalinkForAddArticle(final JSONObject article) throws ServiceException { final Date date = (Date) article.opt(Article.ARTICLE_CREATE_DATE); String ret = article.optString(Article.ARTICLE_PERMALINK); if (StringUtils.isBlank(ret)) { ret = "/articles/" + DateFormatUtils.format(date, "yyyy/MM/dd") + "/" + article.optString(Keys.OBJECT_ID) + ".html"; } if (!ret.startsWith("/")) { ret = "/" + ret; } if (PermalinkQueryService.invalidArticlePermalinkFormat(ret)) { throw new ServiceException(langPropsService.get("invalidPermalinkFormatLabel")); } if (permalinkQueryService.exist(ret)) { throw new ServiceException(langPropsService.get("duplicatedPermalinkLabel")); } return ret.replaceAll(" ", "-"); }
private String volleyPostJsonObjectRequest() { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("phone", "13429667914"); hashMap.put("key", Constant.JUHE_API_KEY); JSONObject object = new JSONObject(hashMap); JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, Constant.JUHE_URL_POST, object, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); } }); request.setTag(JSON_OBJECT_POST_TAG); MyApplication.getHttpQueues().add(request); return request.getTag().toString(); }
/** * reads in the test json for the given test name, gets the tx at the given * index, and verifys that it's transaction type is the expected transaction * type. * * @param testFunctionName * the test function name to use. * @param txIx * the transaction index to use. * @param expectedTransactionType * the expected transaction type to use. */ private void assertTransactionTypeEquals(final String testFunctionName, final int txIx, final TransactionType expectedTransactionType) { try { final String blockJsonStr = TestUtil.getJsonTestResourceAsString(getClass().getSimpleName(), testFunctionName); final JSONObject blockJson = new JSONObject(blockJsonStr); final String blockStr = TestUtil.fromHexJsonObject(blockJson); final byte[] blockBa = Hex.decodeHex(blockStr.toCharArray()); final Block block = new Block(ByteBuffer.wrap(blockBa)); final Transaction tx = block.getTransactionList().get(txIx); final TransactionType actulaTransactionType = tx.type; Assert.assertEquals("transaction types must match", expectedTransactionType, actulaTransactionType); } catch (final Exception e) { throw new RuntimeException(e); } }
private String parseIatResult(String json) { { StringBuffer ret = new StringBuffer(); JSONTokener jsonTokener = new JSONTokener(json); try { JSONObject jsonObject = new JSONObject(jsonTokener); JSONArray jsonArray = jsonObject.getJSONArray("ws"); for (int i = 0; i < jsonArray.length(); ++i) { // 转写结果词,默认使用第一个结果 JSONArray items = jsonArray.getJSONObject(i).getJSONArray("cw"); JSONObject obj = items.getJSONObject(0); // 如果需要多候选结果,解析数组其他字段0 // for(int j = 0; j < items.length(); j++) // { // JSONObject obj = items.getJSONObject(j); // ret.append(obj.getString("w")); // } ret.append(obj.getString("w")); } } catch (JSONException e) { e.printStackTrace(); } return ret.toString(); } }
private void postMakeNewInstance(final String requestedInstanceId, final Boolean makePublic) { AsyncCallbackPair<JSONObject> makeNewGameCallback = new AsyncCallbackPair<JSONObject>(){ public void onSuccess(final JSONObject response) { processInstanceLists(response); NewInstanceMade(InstanceId()); FunctionCompleted("MakeNewInstance"); } public void onFailure(final String message) { WebServiceError("MakeNewInstance", message); } }; postCommandToGameServer(NEW_INSTANCE_COMMAND, Lists.<NameValuePair>newArrayList( new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()), new BasicNameValuePair(GAME_ID_KEY, GameId()), new BasicNameValuePair(INSTANCE_ID_KEY, requestedInstanceId), new BasicNameValuePair(INSTANCE_PUBLIC_KEY, makePublic.toString())), makeNewGameCallback, true); }
/** * 解析和处理服务器返回的省级数据 */ public static boolean handleProvinceResponse(String response) { if(!TextUtils.isEmpty(response)){ try { JSONArray allProvinces = new JSONArray(response); for (int i = 0; i < allProvinces.length(); i++) { JSONObject provinceObject = allProvinces.getJSONObject(i); Province province = new Province(); province.setProvinceName(provinceObject.getString("name")); province.setProvinceCode(provinceObject.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; }
/** * Parse a DebugServerException from the server json string. * @param str json string returned by the debug server * @return A DebugServerException or null if the string is not of proper form. */ @Nullable public static DebugServerException parse(String str) { if (TextUtils.isEmpty(str)) { return null; } try { JSONObject jsonObject = new JSONObject(str); String fullFileName = jsonObject.getString("filename"); return new DebugServerException( jsonObject.getString("description"), shortenFileName(fullFileName), jsonObject.getInt("lineNumber"), jsonObject.getInt("column")); } catch (JSONException e) { // I'm not sure how strict this format is for returned errors, or what other errors there can // be, so this may end up being spammy. Can remove it later if necessary. FLog.w(ReactConstants.TAG, "Could not parse DebugServerException from: " + str, e); return null; } }
void GetResult(Object msg) { if (msg != null && !msg.equals("")) { try { JSONObject jsonObject = new JSONObject(msg + ""); int state = jsonObject.getInt("state"); /** ?movieId=450&mao=pao **/ if (state == 1) { String movieId = HelperSP.getFromSP(this, "movieID", "movieID"); this.finish(); webfun.openNewWindow(Constants.urlPaoPaoEnd + "?movieId=" + movieId + "&mao=pao", true, false, 2); ToastShow("提交成功"); } else { ToastShow("提交失败"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { ToastShow("提交失败"); } }
/** * * 获取决议详情 * * @Description<功能详细描述> * * @param task * @param handler * @param requestType * @param id * @return * @LastModifiedDate:2016年12月2日 * @author wl * @EditHistory:<修改内容><修改人> */ public static NetTask sendGetResolutionInfoRequest(NetTask task, Handler handler, int requestType, String id) { JSONObject bodyVaule = new JSONObject(); try { bodyVaule.put("id", id); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONObject requestObj = NetRequestController.getPredefineObj("resolution", "ResolutionAdapter", "getResolutionInfo", "general", bodyVaule); return NetRequestController.sendStrBaseServlet(task, handler, requestType, requestObj); }
/** * Generates a {@link JSONObject} representing a * Discord-friendly webhook payload. * * <p>This should more than likely never need to be * used if you are contributing a {@link * com.jagrosh.discordwebhooks.Converter Converter}. * * @return A JSONObject, representing a Discord-friendly * webhook payload. */ public JSONObject toJson() { JSONObject json = new JSONObject(); if(username!=null) json.put("username", username); if(avatar!=null) json.put("avatar_url", avatar); if(content.length()!=0) json.put("content", content.toString()); if(tts) json.put("tts", tts); if(!embeds.isEmpty()) { JSONArray array = new JSONArray(); embeds.forEach(e -> array.put(e.toJson())); json.put("embeds", array); } return json; }
protected HashMap<String, String> getEntryFieldsFromIntent() { HashMap<String, String> res = new HashMap<String, String>(); try { JSONObject json = new JSONObject(_intent.getStringExtra(Strings.EXTRA_ENTRY_OUTPUT_DATA)); for(Iterator<String> iter = json.keys();iter.hasNext();) { String key = iter.next(); String value = json.get(key).toString(); Log.d("KP2APluginSDK", "received " + key+"/"+value); res.put(key, value); } } catch (JSONException e) { e.printStackTrace(); } return res; }
public static UpdateInfo parse(JSONObject jsonObject){ try { UpdateInfo updateModel = new UpdateInfo(); String JsonNewVersion = jsonObject.getString(KEY_LATEST_VERSION).trim(); String JsonApkUrl = jsonObject.getString(KEY_URL); if (JsonNewVersion == null || JsonNewVersion.length() == 0) { throw new IllegalArgumentException("Argument JsonNewVersion cannot be null or empty"); } if (JsonApkUrl == null || JsonApkUrl.length() == 0) { throw new IllegalArgumentException("Argument JsonApkUrl cannot be null or empty"); } updateModel.setVersion(JsonNewVersion); updateModel.setUrl(JsonApkUrl); JSONArray releaseArr = jsonObject.optJSONArray(KEY_RELEASE_NOTES); StringBuilder builder = new StringBuilder(); for(int i = 0; i < releaseArr.length(); ++i) { builder.append(releaseArr.getString(i).trim()); builder.append(System.getProperty("line.separator")); } updateModel.setNotes(builder.toString()); return updateModel; } catch (JSONException e){ if (BuildConfig.DEBUG){ Log.e(AppVerUpdater.TAG, "The JSON updater file is mal-formatted."); } } return null; }
public static String toCSS(JSONObject urp) { Properties props = new Properties(); String[] names = JSONObject.getNames(urp); for (String prop : names) { props.setProperty(prop, urp.get(prop).toString()); } return toCSS(props); }
public boolean isAppIdReady(QNResultCallback callback) { String checkedAppString = FileUtils.getStringFromFileWithDecrypt(getCheckFilename()); int result = 0; if (checkedAppString != null) { try { result = new JSONObject(checkedAppString).getInt("result"); } catch (JSONException e) { e.printStackTrace(); } } int apiResult = 0; if (result == 0) { if (callback != null) { QNLog.error("appId 还未校验"); } apiResult = 1; } else if (result == 1) { if (callback != null) { QNLog.error("appId 校验失败,请检查您的appId"); } apiResult = 1; } else if (result == 2) { if (callback != null) { QNLog.error("SDK版本过低,请升级SDK"); } apiResult = 8; } if (!(result == 4 || callback == null)) { callback.onCompete(apiResult); } if (result == 4) { return true; } return false; }
protected JSONObject DemoBatchSetTag() throws JSONException { XingeClient xinge = new XingeClient(000, "secret_key"); List<TagTokenPair> pairs = new ArrayList<TagTokenPair>(); // 切记把这里的示例tag和示例token修改为你的真实tag和真实token pairs.add(new TagTokenPair("tag1","token00000000000000000000000000000000001")); pairs.add(new TagTokenPair("tag2","token00000000000000000000000000000000001")); JSONObject ret = xinge.BatchSetTag(pairs); return (ret); }
private void parseJSON(String data) throws JSONException { if (data == null) return; Route route = null; List<Route> routes = new ArrayList<>(); JSONObject jsonData = new JSONObject(data); JSONArray jsonRoutes = jsonData.getJSONArray("routes"); for (int i = 0; i < jsonRoutes.length(); i++) { JSONObject jsonRoute = jsonRoutes.getJSONObject(i); route = new Route(); JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline"); JSONArray jsonLegs = jsonRoute.getJSONArray("legs"); JSONObject jsonLeg = jsonLegs.getJSONObject(0); JSONObject jsonDistance = jsonLeg.getJSONObject("distance"); JSONObject jsonDuration = jsonLeg.getJSONObject("duration"); JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location"); JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location"); route.setDistance(new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"))); route.setDuration(new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"))); route.setEndAddress(jsonLeg.getString("end_address")); route.setStartAddress(jsonLeg.getString("start_address")); route.setStartLocation(new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"))); route.setEndLocation(new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"))); route.setPoints(decodePolyLine(overview_polylineJson.getString("points"))); routes.add(route); } listener.onDirectionFinderSuccess(routes, route); }
/** * 返给js错误数据 * * @param errorCode * @param errorMsg */ private void callBackErrorData(int errorCode, String errorMsg) { JSONObject jsonData = new JSONObject(); try { jsonData.put("ErrorCode", errorCode); jsonData.put("ErrorMsg", errorMsg); jsonData.put("JsonResult", null); callCallback(String.valueOf(what), jsonData.toString()); } catch (JSONException e) { e.printStackTrace(); } }
public JSONObject getByOrder(final int order) throws RepositoryException { final Query query = new Query().setFilter(new PropertyFilter(Page.PAGE_ORDER, FilterOperator.EQUAL, order)) .setPageCount(1); final JSONObject result = get(query); final JSONArray array = result.optJSONArray(Keys.RESULTS); if (0 == array.length()) { return null; } return array.optJSONObject(0); }
public PurchaseSalesOrderConfig(JSONObject jsonObject) { if (jsonObject != null && jsonObject.length() > 0) { try { JSONArray jsonArray = jsonObject.getJSONArray(ENTITY_TAGS); et = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { Object obj = jsonArray.get(i); et.add((String) obj); } } catch (JSONException e) { et = new ArrayList<>(1); } if (jsonObject.get(SALES_ORDER_APPROVAL) != null) { soa = jsonObject.getBoolean(SALES_ORDER_APPROVAL); } if (jsonObject.get(PURCHASE_ORDER_APPROVAL) != null) { poa = jsonObject.getBoolean(PURCHASE_ORDER_APPROVAL); } if (jsonObject.get(SALES_ORDER_APPROVAL_CREATION) != null) { soac = jsonObject.getBoolean(SALES_ORDER_APPROVAL_CREATION); } if (jsonObject.get(SALES_ORDER_APPROVAL_SHIPPING) != null) { soas = jsonObject.getBoolean(SALES_ORDER_APPROVAL_SHIPPING); } } }
private JSONObject serializeWifiInfo(WifiInfo data) throws JSONException { JSONObject result = new JSONObject(mGson.toJson(data)); result.put("SSID", trimQuotationMarks(data.getSSID())); for (SupplicantState state : SupplicantState.values()) { if (data.getSupplicantState().equals(state)) { result.put("SupplicantState", state.name()); } } return result; }
public static void sendAsynchCommand(final OutputStream out, final CommandEnum command, final Optional<ByteArraySerializable> payload, final JSONObject error) throws IOException { final byte[] payloadBa; if (payload.isPresent()) { payloadBa = payload.get().toByteArray(); } else { payloadBa = new byte[0]; } final Message requestMessage = new Message(TestUtil.MAIN_NET_MAGIC, command, payloadBa); final byte[] requestBa = requestMessage.toByteArray(); LOG.info(">>>:{}", Hex.encodeHexString(requestBa)); out.write(requestBa); }
/** * * @param context the context from the Activity * @param script raw data extracted with JSoup from a script tag in the HTML page */ GraphExtractor(Context context, String script) { this.context = context; Log.d(TAG, "todo graph"); // Remove formatter script = script.replaceAll("formatter:([^`])*\\}", "}"); // Remove extra comma script = script.replaceAll(",([^a-z])*\\}", "}"); // Remove values between simple quotes (like '<style>some code with "</style>') script = script.replaceAll("'.*'", "\"\""); // Fix missing double quotes script = script.replaceAll("(['\"])?([a-zA-Z0-9_-]+)(['\"])?( )?:", "\"$2\":"); String beginExpr = "new Highcharts.Chart({"; int beginIndex = script.indexOf(beginExpr) + beginExpr.length() - 1; if (beginIndex != -1) { int endIndex = script.indexOf("});", beginIndex); if (endIndex != -1) { try { String rawChart = script.substring(beginIndex, endIndex + 1) + "}"; data = new JSONObject(rawChart); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } } }