Java Code Examples for org.json.JSONObject

The following are top voted examples for showing how to use org.json.JSONObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: chromium-for-android-56-debug-video   File: CastMessageHandler.java   Source Code and License 13 votes vote down vote up
/**
 * 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));
            }
        }
    }
}
 
Example 2
Project: Android-Code-Demos   File: MainActivity.java   Source Code and License 7 votes vote down vote up
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();
}
 
Example 3
Project: neo-java   File: TestBlockSerialization.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
	}
}
 
Example 4
Project: FastAndroid   File: Recognizer.java   Source Code and License 7 votes vote down vote up
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();
        }

    }
 
Example 5
Project: YunPengWeather   File: Utility.java   Source Code and License 7 votes vote down vote up
/**
 * 解析和处理服务器返回的省级数据
 */
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;
}
 
Example 6
Project: Banmanager   File: JSONUtils.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 7
Project: boohee_v5.6   File: LEYUApplication.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 8
Project: EARLGREY   File: Properties.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 9
Project: bayou   File: ApiSynthesisServlet.java   Source Code and License 6 votes vote down vote up
@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");
    }
}
 
Example 10
Project: OCast-Java   File: Payload.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 11
Project: android-mobile-engage-sdk   File: IamJsBridge.java   Source Code and License 6 votes vote down vote up
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);
            }
        });
    }
}
 
Example 12
Project: Pocket-Plays-for-Twitch   File: VideoCastManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
                    }
                }
            });
}
 
Example 13
Project: MultiViewAdapter   File: DataBindingActivity.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 14
Project: edoras-one-initializr   File: InitializrMetadataV2JsonMapper.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 15
Project: openrouteservice   File: JsonMapMatchingRequestProcessor.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 16
Project: SearchRestaurant   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 17
Project: NotiCap   File: FilterRule.java   Source Code and License 6 votes vote down vote up
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");
}
 
Example 18
Project: adyo-android   File: GetPlacementRequest.java   Source Code and License 6 votes vote down vote up
@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;

}
 
Example 19
Project: boohee_v5.6   File: a.java   Source Code and License 6 votes vote down vote up
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) {
                    }
                }
            }
        }
    }
}
 
Example 20
Project: coolweater   File: Utility.java   Source Code and License 6 votes vote down vote up
/**
 * 解析和处理服务器返回的省级数据
 */
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;
}
 
Example 21
Project: fpc   File: DpnAPI2.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
    };
}
 
Example 22
Project: Banmanager   File: JSONUtils.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 23
Project: solo-spring   File: ArticleMgmtService.java   Source Code and License 6 votes vote down vote up
/**
 * 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(" ", "-");
}
 
Example 24
Project: appinventor-extensions   File: GameClient.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 25
Project: RNLearn_Project1   File: DebugServerException.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example 26
Project: PaoMovie   File: SendPaoPaoAudio.java   Source Code and License 6 votes vote down vote up
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("提交失败");
	}
}
 
Example 27
Project: amap   File: ResolutionSeviceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * 获取决议详情
 * 
 * @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);
}
 
Example 28
Project: DiscordWebhooks   File: WebhookResponse.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 29
Project: keepass2android   File: PluginActionBroadcastReceiver.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 30
Project: AppVerUpdater   File: JSONParser.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 31
Project: marathonv5   File: PropertyHelper.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 32
Project: boohee_v5.6   File: QNApiImpl.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 33
Project: raven   File: Demo.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 34
Project: AppGoogleMaps   File: DownloadRawData.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 35
Project: hybrid   File: IndexWebActivityNew.java   Source Code and License 5 votes vote down vote up
/**
 * 返给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();
    }
}
 
Example 36
Project: solo-spring   File: PageDao.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 37
Project: logistimo-web-service   File: ApprovalsConfig.java   Source Code and License 5 votes vote down vote up
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);
    }
  }
}
 
Example 38
Project: mobly-bundled-snippets   File: JsonSerializer.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 39
Project: neo-java   File: TestUtil.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 40
Project: LeMondeRssReader   File: GraphExtractor.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @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());
            }
        }
    }
}
 
Example 41
Project: JDA-Audio   File: WebSocketExample.java   Source Code and License 5 votes vote down vote up
@Override
public void sendWS(String message)
{
    JSONObject obj = new JSONObject();
    obj.put("action", "SEND_WS");
    obj.put("identifier", identifier);
    obj.put("message", message);

    socket.sendText(obj.toString());
}
 
Example 42
Project: JavAMP   File: ScheduleData.java   Source Code and License 5 votes vote down vote up
public ScheduleData(final JSONObject json)
{
    this.json = json;
    this.availableMethods = new AvailableMethods(json.getJSONArray("AvailableMethods"));
    this.availableTriggers = new AvailableTriggers(json.getJSONArray("AvailableTriggers"));
    this.populatedTriggers = new PopulatedTriggers(json.getJSONArray("PopulatedTriggers"));
}
 
Example 43
Project: JavAMP   File: ServerManager.java   Source Code and License 5 votes vote down vote up
/**
 * Get the info of a user on the server.
 *
 * @param uid The user ID of the user to get the info of.
 * @return Serialized response from the panel.
 */
public User getUserInfo(final String uid) throws UnknownUserException
{
    final JSONObject arguments = new JSONObject();
    arguments.put("UID", uid);
    final Request request = new Request(Requests.GET_USER_INFO.getUrl(), arguments);
    return new User(request.send(this.session));
}
 
Example 44
Project: localcloud_fe   File: JSONHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Converts location data into a JSON form that can be consumed within a JavaScript application
 * @param provider Indicates if this location is coming from gps or network provider
 * @param location The android Location
 * @param cached Indicates if the value was pulled from the device cache or not
 * @param buffer Boolean indicates whether or not buffering is activated
 * @param bufferLat The buffer's geometric latitudinal center.
 * @param bufferedLon The buffer's geometric longitudinal center.
 * @param bufferedAccuracy The buffer's average accuracy.
 * @param bufferSize The number of elements within the buffer
 * @return Location data. Note: this library returns 0 rather than null to avoid nullPointExceptions
 */
public static String locationJSON(
        String provider,
        Location location,
        boolean cached,
        boolean buffer,
        double bufferLat,
        double bufferedLon,
        float bufferedAccuracy,
        int bufferSize) {

    final JSONObject json = new JSONObject();

    if(location != null){
        try {

            json.put("provider", provider);
            json.put("timestamp", location.getTime());
            json.put("latitude", location.getLatitude());
            json.put("longitude", location.getLongitude());
            json.put("altitude", location.getAltitude());
            json.put("accuracy", location.getAccuracy());
            json.put("bearing", location.getBearing());
            json.put("speed", location.getSpeed());
            json.put("cached", cached);
            json.put("buffer", buffer);
            json.put("bufferSize", bufferSize);
            json.put("bufferedLatitude", bufferLat);
            json.put("bufferedLongitude", bufferedLon);
            json.put("bufferedAccuracy", bufferedAccuracy);
        }
        catch (JSONException exc) {
            logJSONException(exc);
        }
    }

    return json.toString();
}
 
Example 45
Project: vrops-export   File: Exporter.java   Source Code and License 5 votes vote down vote up
private JSONObject fetchResources(String resourceKind, String adapterKind, String name, int page) throws JSONException, IOException, HttpException {
	String url = "/suite-api/api/resources";
	ArrayList<String> qs = new ArrayList<>();
	if(adapterKind != null)
		qs.add("adapterKind=" + adapterKind);
	qs.add("resourceKind=" + resourceKind);
	qs.add("pageSize=" + PAGE_SIZE);
	qs.add("page=" + page);
	if(name != null)
		qs.add("name=" + name);
	JSONObject response = client.getJson(url, qs); 
	if(verbose)
		System.err.println("Resources found: " + response.getJSONObject("pageInfo").getInt("totalCount"));
	return response;
}
 
Example 46
Project: JTradfri   File: TradfriDevice.java   Source Code and License 5 votes vote down vote up
public void setColor(String color) {
	if(color.length() != 6) {
		return;
	}
	
	color = color.toLowerCase();
	
	JSONObject json = new JSONObject();
	json.put("3311", new JSONArray().put(0, new JSONObject().put("5706", color)));
	
	gateway.putJSON("/15001/" + Integer.toString(this.deviceID), json.toString());
	
	this.color = color;
}
 
Example 47
Project: rapid-io-android   File: FilterValue.java   Source Code and License 5 votes vote down vote up
@Override
public Object toJson() throws JSONException {
	if(compareType.equals(TYPE_EQUAL)) {
		return value;
	} else {
		JSONObject root = new JSONObject();
		root.put(compareType, value);
		return root.toString();
	}
}
 
Example 48
Project: ClouldReader   File: ACache.java   Source Code and License 5 votes vote down vote up
/**
 * 读取JSONObject数据
 * 
 * @param key
 * @return JSONObject数据
 */
public JSONObject getAsJSONObject(String key) {
	String JSONString = getAsString(key);
	try {
		JSONObject obj = new JSONObject(JSONString);
		return obj;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 49
Project: Simpler   File: Topic.java   Source Code and License 5 votes vote down vote up
public static Topic parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }

    Topic user = new Topic();
    user.name = jsonObject.optString("card_type_name", "");
    user.topic = jsonObject.optString("title_sub", "");
    user.picUrl = jsonObject.optString("pic", "");
    user.desc1 = jsonObject.optString("desc1", "");
    user.desc2 = jsonObject.optString("desc2", "");
    if (!"".equals(user.picUrl)) {
        user.picUrl = user.picUrl.replace("/thumbnail/", "/bmiddle/");
    }
    return user;
}
 
Example 50
Project: alfresco-repository   File: SolrQueryHTTPClient.java   Source Code and License 5 votes vote down vote up
protected JSONObject buildStatsBody(StatsParameters searchParameters, String tenant, Locale locale) throws JSONException
{
    JSONObject body = new JSONObject();
    body.put("query", searchParameters.getQuery());
    
    JSONArray tenants = new JSONArray();
    tenants.put(tenant);
    body.put("tenants", tenants);
    
    JSONArray locales = new JSONArray();
    locales.put(locale);
    body.put("locales", locales);
    
    return body;
}
 
Example 51
Project: marathonv5   File: Marathon.java   Source Code and License 5 votes vote down vote up
private String convertToJSON(List<Map<Object, Object>> v) {
    JSONArray ja = new JSONArray();
    for (Map<Object, Object> map : v) {
        Properties p = new Properties();
        Set<Object> keySet = map.keySet();
        for (Object object : keySet) {
            p.setProperty(object.toString(), map.get(object).toString());
        }
        ja.put(new JSONObject(p));
    }
    return ja.toString();
}
 
Example 52
Project: alfresco-remote-api   File: RuleServiceTest.java   Source Code and License 5 votes vote down vote up
public void testGetActionConstraints() throws Exception
{
    Response response = sendRequest(new GetRequest(URL_ACTIONCONSTRAINTS), 200);
    JSONObject result = new JSONObject(response.getContentAsString());

    assertNotNull(result);

    assertTrue(result.has("data"));

    JSONArray data = result.getJSONArray("data");

    for (int i = 0; i < data.length(); i++)
    {
        JSONObject actionConstraint = data.getJSONObject(i);

        assertTrue(actionConstraint.has("name"));
        assertTrue(actionConstraint.has("values"));

        JSONArray values = actionConstraint.getJSONArray("values");

        for (int j = 0; j < values.length(); j++)
        {
            JSONObject value = values.getJSONObject(j);

            assertTrue(value.has("value"));
            assertTrue(value.has("displayLabel"));
        }
    }
}
 
Example 53
Project: logistimo-web-service   File: AuthenticateOutput.java   Source Code and License 5 votes vote down vote up
public static Hashtable loadReasonsByTag(JSONObject json) throws JSONException {
  Hashtable reasonsByTagHt = new Hashtable();
  // Enumeration en = json.keys();
  Iterator en = json.keys();
  //  while ( en.hasMoreElements() ) {
  while (en.hasNext()) {
    //  String transType = (String) en.nextElement();
    String transType = (String) en.next();
    JSONObject tagsByTransJson = json.getJSONObject(transType);
    if (tagsByTransJson == null) {
      continue;
    }
    Iterator enTags = tagsByTransJson.keys();
    // Enumeration enTags = tagsByTransJson.keys();
    Hashtable tagsHt = new Hashtable();
    // while ( enTags.hasMoreElements() ) {
    //   String tag = (String) enTags.nextElement();
    while (enTags.hasNext()) {
      String tag = (String) enTags.next();
      String value = null;
      if ((value = (String) tagsByTransJson.get(tag)) != null && !value.equals("")) {
        tagsHt.put(tag, value);
      }
    }
    reasonsByTagHt.put(transType, tagsHt);
  }
  return reasonsByTagHt;
}
 
Example 54
Project: Xndroid   File: FqrouterManager.java   Source Code and License 5 votes vote down vote up
private static int getHttpManagerPort() {
    File configFile = new File(sXndroidFile + "/fqrouter/etc/fqsocks.json");
    if (!configFile.exists()) {
        Log.w("xndroid_log", "fqsocks.json don't exist");
        return 2515;
    }
    try {
        FileInputStream input = new FileInputStream(configFile);
        JSONObject json = new JSONObject(HttpJson.streamToString(input));
        return json.getJSONObject("http_manager").getInt("port");
    } catch (Exception e) {
        Log.e("xndroidLog", "failed to parse config", e);
        return 2515;
    }
}
 
Example 55
Project: alfresco-remote-api   File: SubscriptionServiceRestApiTest.java   Source Code and License 5 votes vote down vote up
protected void setSubscriptionListPrivate(String user, boolean setPrivate) throws Exception
{
    JSONObject privateObject = new JSONObject();
    privateObject.put("private", setPrivate);

    String url = getUrl(URL_PRIVATE, user);
    Response response = sendRequest(new PutRequest(url, privateObject.toString(), "application/json"),
            Status.STATUS_OK);

    JSONObject resultObject = new JSONObject(response.getContentAsString());
    assertTrue(resultObject.has("private"));
    assertEquals(setPrivate, resultObject.getBoolean("private"));
}
 
Example 56
Project: li-android-sdk-core   File: LiUriUtils.java   Source Code and License 5 votes vote down vote up
public static Uri getUri(
        @NonNull JSONObject json,
        @NonNull String field)
        throws JSONException {
    LiCoreSDKUtils.checkNotNull(json, "json must not be null");
    LiCoreSDKUtils.checkNotNull(field, "field must not be null");

    String value = json.getString(field);
    if (value == null) {
        throw new JSONException("field \"" + field + "\" is mapped to a null value");
    }
    return Uri.parse(value);
}
 
Example 57
Project: LiuAGeAndroid   File: NewsDALManager.java   Source Code and License 5 votes vote down vote up
/**
 * 从本地缓存加载资讯数据列表
 *
 * @param classid          分类id
 * @param newsListCallback 资讯列表回调
 */
public void loadNewsListFromLocal(String classid, final NewsListCallback newsListCallback) {

    int preCount = 0;
    int oneCount = 20;
    JSONArray jsonArray = new JSONArray();
    // 其他分类
    List<NewsListOtherCache> otherCaches = DataSupport.order("id asc").where("classid = ?", classid).limit(oneCount).offset(preCount).find(NewsListOtherCache.class);
    for (NewsListOtherCache otherCache :
            otherCaches) {
        try {
            JSONObject jsonObject = new JSONObject(otherCache.getNews());
            jsonArray.put(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
            newsListCallback.onError("数据解析失败");
            break;
        }
    }

    if (jsonArray.length() > 0) {
        newsListCallback.onSuccess(jsonArray);
        LogUtils.d(TAG, "加载到缓存其他分类数据 = " + jsonArray.toString());
    } else {
        newsListCallback.onError("没有本地数据");
    }

}
 
Example 58
Project: Nearby   File: Supporter.java   Source Code and License 5 votes vote down vote up
public void convertSrt(JSONObject temp){
    ArrayList<String> keySet = AdditionalFunc.getKeySet(temp.keys());

    try {

        if (keySet.contains("user_id")) {
            id = (String) temp.get("user_id");
        }
        if (keySet.contains("user_login_id")) {
            loginId = (String) temp.get("user_login_id");
        }
        if (keySet.contains("user_email")) {
            email = (String) temp.get("user_email");
        }
        if (keySet.contains("user_first_name")) {
            fn = (String) temp.get("user_first_name");
        }
        if (keySet.contains("user_last_name")) {
            ln = (String) temp.get("user_last_name");
        }
        if (keySet.contains("user_phone")) {
            phone = (String) temp.get("user_phone");
        }
        if (keySet.contains("relationship")){
            relationship = (String) temp.get("relationship");
        }

    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 59
Project: alerta-fraude   File: FileUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a JSON object representing the given File. Internal APIs should be modified
 * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
 *
 * @param file the File to convert
 * @return a JSON representation of the given File
 * @throws JSONException
 */
public JSONObject getEntryForFile(File file) throws JSONException {
    JSONObject entry;

    for (Filesystem fs : filesystems) {
         entry = fs.makeEntryForFile(file);
         if (entry != null) {
             return entry;
         }
    }
    return null;
}
 
Example 60
Project: open-rmbt   File: JSONParser.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param object
 * @return
 * @throws JSONException
 */
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<String, Object>();
    Iterator<?> keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.get(key)));
    }
    return map;
}