Java Code Examples for org.json.JSONObject#optString()

The following examples show how to use org.json.JSONObject#optString() . 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: ChatComponentParser.java    From Angelia-core with GNU General Public License v3.0 6 votes vote down vote up
private static ClickEvent parseClickEvent(JSONObject json, Logger logger) {
	String key = json.optString("action", null);
	if (key == null) {
		logger.warn("Received invalid click event with no action, ignoring it: " + json.toString());
		return null;
	}
	String value = json.optString("value", null);
	if (value == null) {
		logger.warn("Received invalid click event with no value, ignoring it: " + json.toString());
		return null;
	}
	switch (key.toLowerCase()) {
	case "open_url":
		return new ClickEvent(ClickEvent.Action.OPEN_URL, value);
	case "run_command":
		return new ClickEvent(ClickEvent.Action.RUN_COMMAND, value);
	case "suggest_command":
		return new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, value);
	case "change_page":
		return new ClickEvent(ClickEvent.Action.CHANGE_PAGE, value);
	default:
		logger.warn("Unknown key " + key + " for click event, ignoring it: " + json.toString());
		return null;
	}
}
 
Example 2
Source File: Purchase.java    From secrecy with Apache License 2.0 6 votes vote down vote up
/**
 * @param itemType         the item type for this purchase, cannot be null.
 * @param jsonPurchaseInfo the JSON representation of this purchase
 * @param signature        the signature
 * @throws JSONException if the purchase cannot be parsed or is invalid.
 */
public Purchase(ItemType itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    if (itemType == null) throw new IllegalArgumentException("itemType cannot be null");
    mItemType = itemType;
    final JSONObject json = new JSONObject(jsonPurchaseInfo);

    mOrderId = json.optString(ORDER_ID);
    mPackageName = json.optString(PACKAGE_NAME);
    mSku = json.optString(PRODUCT_ID);
    mPurchaseTime = json.optLong(PURCHASE_TIME);
    mPurchaseState = json.optInt(PURCHASE_STATE);
    mDeveloperPayload = json.optString(DEVELOPER_PAYLOAD);
    mToken = json.optString(TOKEN, json.optString(PURCHASE_TOKEN));

    mOriginalJson = jsonPurchaseInfo;
    mSignature = signature;
    mState = State.fromCode(mPurchaseState);

    if (TextUtils.isEmpty(mSku)) {
        throw new JSONException("SKU is empty");
    }
}
 
Example 3
Source File: Push4FreshCommentParser.java    From JianDan_OkHttp with Apache License 2.0 6 votes vote down vote up
@Nullable
public Boolean parse(Response response) {

    code = wrapperCode(response.code());
    if (!response.isSuccessful())
        return null;

    try {
        JSONObject resultObj = new JSONObject(response.body().string());
        String result = resultObj.optString("status");
        if (result.equals("ok")) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 4
Source File: VKApiUser.java    From cordova-social-vk with Apache License 2.0 6 votes vote down vote up
/**
 * Fills an user object from server response.
 */
public VKApiUser parse(JSONObject from) {
    super.parse(from);
    first_name = from.optString("first_name", first_name);
    last_name = from.optString("last_name", last_name);
    online = ParseUtils.parseBoolean(from, FIELD_ONLINE);
    online_mobile = ParseUtils.parseBoolean(from, FIELD_ONLINE_MOBILE);

 photo_50 = addSquarePhoto(from.optString(FIELD_PHOTO_50, photo_50), 50);
 photo_100 = addSquarePhoto(from.optString(FIELD_PHOTO_100, photo_100), 100);
 photo_200 = addSquarePhoto(from.optString(FIELD_PHOTO_200, photo_200), 200);

 photo_400_orig = from.optString(FIELD_PHOTO_400_ORIGIN, photo_400_orig);
 photo_max = from.optString(FIELD_PHOTO_MAX, photo_max);
 photo_max_orig = from.optString(FIELD_PHOTO_MAX_ORIGIN, photo_max_orig);
 photo_big = from.optString(FIELD_PHOTO_BIG, photo_big);

    photo.sort();
    return this;
}
 
Example 5
Source File: SendBuddyMsgResult.java    From MaterialQQLite with Apache License 2.0 6 votes vote down vote up
public boolean parse(byte[] bytData) {
	try {
		reset();
		
		if (bytData == null || bytData.length <= 0)
			return false;
		
		String strData = new String(bytData, "UTF-8");
		System.out.println(strData);
		
		JSONObject json = new JSONObject(strData);
		m_nRetCode = json.optInt("retcode");
		m_strResult = json.optString("result");
		
		return true;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return false;
}
 
Example 6
Source File: Users.java    From authy-java with MIT License 6 votes vote down vote up
private Hash instanceFromJson(int status, String content) throws AuthyException {
    Hash hash = new Hash(status, content);
    if (hash.isOk()) {
        try {
            JSONObject jsonResponse = new JSONObject(content);
            String message = jsonResponse.optString("message");
            hash.setMessage(message);

            boolean success = jsonResponse.optBoolean("success");
            hash.setSuccess(success);

            String token = jsonResponse.optString("token");
            hash.setToken(token);
        } catch (JSONException e) {
            throw new AuthyException("Invalid response from server", e);
        }
    } else {
        Error error = errorFromJson(content);
        hash.setError(error);
    }

    return hash;
}
 
Example 7
Source File: MarketDepthAsksResponse.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public void from(JSONObject obj) {
	if (obj != null) {
		this.id = obj.optInt("id");
		this.status = obj.optString("status");
		this.type = obj.optString("type");
		this.result.from(obj.optJSONObject("result"));
	}
}
 
Example 8
Source File: BusSupport.java    From Tangram-Android with MIT License 5 votes vote down vote up
/**
     * This performs the same feature as {@link #wrapEventHandler(String, String, Object, String)}, just parse the params from jsonObject.
     *
     * @param subscriber Original subscriber object
     * @param jsonObject Json params
     * @return An EventHandlerWrapper wrapping a subscriber and used to registered into event bus.
     */
    public static EventHandlerWrapper wrapEventHandler(@NonNull Object subscriber, @NonNull JSONObject jsonObject) {
        String type = jsonObject.optString("type");
        if (TextUtils.isEmpty(type)) {
            return null;
        }
        String producer = jsonObject.optString("producer");
//        String subscriber = jsonObject.optString("subscriber");
        String action = jsonObject.optString("action");
        return new EventHandlerWrapper(type, producer, subscriber, action);
    }
 
Example 9
Source File: NameFind.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public static String getAddress(String name) throws Exception {
	String result = _caches.get(name);
	if (result == null) {
		if (name.startsWith("~")) {
			name = name.substring(1, name.length());
		}
		String web = page + "/user/" + name;
		result = HttpRequest.getHttps(web);
		if (result != null) {
			JSONObject obj = new JSONObject(result);
			result = obj.optString("address", null);
			if (result != null) {
				_caches.put(name, result);
			}
		}
	}
	if (result == null) {
		if (name.startsWith("~")) {
			name = name.substring(1, name.length());
		}
		if (Gateway.getAddress(name) != null) {
			ArrayList<Gateway.Item> items = Gateway.getAddress(name).accounts;
			if (items.size() > 0) {
				result = items.get(0).address;
				if (result != null) {
					_caches.put(name, result);
				}
			}
		}
	}
	return result;
}
 
Example 10
Source File: VKApiPoll.java    From cordova-social-vk with Apache License 2.0 5 votes vote down vote up
/**
 * Fills a Poll instance from JSONObject.
 */
public VKApiPoll parse(JSONObject source) {
    id = source.optInt("id");
    owner_id = source.optInt("owner_id");
    created = source.optLong("created");
    question = source.optString("question");
    votes = source.optInt("votes");
    answer_id = source.optInt("answer_id");
    answers = new VKList<Answer>(source.optJSONArray("answers"), Answer.class);
    return this;
}
 
Example 11
Source File: JsonApplier.java    From oxAuth with MIT License 5 votes vote down vote up
public void apply(JSONObject source, Object target, PropertyDefinition property) {
    try {
        if (!source.has(property.getJsonName())) {
            return;
        }
        if (!isAllowed(source, target, property, target.getClass())) {
            return;
        }

        Field field = target.getClass().getDeclaredField(property.getJavaTargetPropertyName());
        field.setAccessible(true);


        Object valueToSet = null;

        if (String.class.isAssignableFrom(property.getJavaType())) {
            valueToSet = source.optString(property.getJsonName());
        }
        if (Collection.class.isAssignableFrom(property.getJavaType())) {
            final JSONArray jsonArray = source.getJSONArray(property.getJsonName());
            valueToSet = jsonArray.toList();
        }

        field.set(target, valueToSet);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
 
Example 12
Source File: VoteProcessor.java    From symphonyx with Apache License 2.0 5 votes vote down vote up
/**
 * Votes up an article.
 *
 * <p>
 * The request json object:
 * <pre>
 * {
 *   "dataId": ""
 * }
 * </pre>
 * </p>
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @param id data id
 * @throws Exception exception
 */
@RequestProcessing(value = "/api/v1/stories/{id}/upvote", method = HTTPRequestMethod.POST)
public void voteUpArticle(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response, final String id) throws Exception {
    final String auth = request.getHeader("Authorization");
    if (auth == null) {//TODO validate
        return;
    }
    final String email = new JSONObject(auth.substring("Bearer ".length())).optString("userEmail");

    final JSONObject currentUser = userQueryService.getUserByEmail(email);
    if (null == currentUser) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    final String userId = currentUser.optString(Keys.OBJECT_ID);
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);

    final JSONObject ret = Results.falseResult();
    renderer.setJSONObject(ret);

    if (voteQueryService.isOwn(userId, id, Vote.DATA_TYPE_C_ARTICLE)) {
        ret.put(Keys.STATUS_CODE, false);
        ret.put(Keys.MSG, langPropsService.get("cantVoteSelfLabel"));

        return;
    }

    final int vote = voteQueryService.isVoted(userId, id);
    if (Vote.TYPE_C_UP == vote) {
        voteMgmtService.voteCancel(userId, id, Vote.DATA_TYPE_C_ARTICLE);
    } else {
        voteMgmtService.voteUpArticle(userId, id);
    }

    ret.put(Vote.TYPE, vote);
    ret.put(Keys.STATUS_CODE, true);
}
 
Example 13
Source File: Tokens.java    From authy-java with MIT License 5 votes vote down vote up
private Token tokenFromJson(int status, String content) throws AuthyException {
    if (status == 200) {
        try {
            JSONObject tokenJSON = new JSONObject(content);
            String message = tokenJSON.optString("message");
            return new Token(status, content, message);

        } catch (JSONException e) {
            throw new AuthyException("Invalid response from server", e, status);
        }
    }

    final Error error = errorFromJson(content);
    throw new AuthyException("Invalid token", status, error.getCode());
}
 
Example 14
Source File: ApiErrorResponse.java    From socialmediasignup with MIT License 4 votes vote down vote up
public static ApiErrorResponse build(JSONObject jsonErr) throws JSONException {
    return new ApiErrorResponse(jsonErr, jsonErr.optInt(ERROR_CODE, -1), jsonErr.optString(MESSAGE),
            jsonErr.optString(REQUEST_ID), jsonErr.optInt(STATUS, -1), jsonErr.optLong(TIMESTAMP, 0));
}
 
Example 15
Source File: FacebookRequestError.java    From facebooklogin with MIT License 4 votes vote down vote up
static FacebookRequestError checkResponseAndCreateError(JSONObject singleResult,
                                                        Object batchResult,
                                                        HttpURLConnection connection) {
    try {
        if (singleResult.has(CODE_KEY)) {
            int responseCode = singleResult.getInt(CODE_KEY);
            Object body = Utility.getStringPropertyAsJSON(singleResult,
                                                          BODY_KEY,
                                                          NON_JSON_RESPONSE_PROPERTY);

            if (body != null && body instanceof JSONObject) {
                JSONObject jsonBody = (JSONObject) body;
                // Does this response represent an error from the service? We might get
                // either an "error"
                // with several sub-properties, or else one or more top-level fields
                // containing error info.
                String errorType = null;
                String errorMessage = null;
                int errorCode = INVALID_ERROR_CODE;
                int errorSubCode = INVALID_ERROR_CODE;

                boolean hasError = false;
                if (jsonBody.has(ERROR_KEY)) {
                    // We assume the error object is correctly formatted.
                    JSONObject error =
                        (JSONObject) Utility.getStringPropertyAsJSON(jsonBody, ERROR_KEY, null);

                    errorType = error.optString(ERROR_TYPE_FIELD_KEY, null);
                    errorMessage = error.optString(ERROR_MESSAGE_FIELD_KEY, null);
                    errorCode = error.optInt(ERROR_CODE_FIELD_KEY, INVALID_ERROR_CODE);
                    errorSubCode = error.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE);
                    hasError = true;
                } else if (jsonBody.has(ERROR_CODE_KEY)
                    || jsonBody.has(ERROR_MSG_KEY)
                    || jsonBody.has(ERROR_REASON_KEY)) {
                    errorType = jsonBody.optString(ERROR_REASON_KEY, null);
                    errorMessage = jsonBody.optString(ERROR_MSG_KEY, null);
                    errorCode = jsonBody.optInt(ERROR_CODE_KEY, INVALID_ERROR_CODE);
                    errorSubCode = jsonBody.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE);
                    hasError = true;
                }

                if (hasError) {
                    return new FacebookRequestError(responseCode,
                                                    errorCode,
                                                    errorSubCode,
                                                    errorType,
                                                    errorMessage,
                                                    jsonBody,
                                                    singleResult,
                                                    batchResult,
                                                    connection);
                }
            }

            // If we didn't get error details, but we did get a failure response code,
            // report it.
            if (!HTTP_RANGE_SUCCESS.contains(responseCode)) {
                return new FacebookRequestError(responseCode,
                                                INVALID_ERROR_CODE,
                                                INVALID_ERROR_CODE,
                                                null,
                                                null,
                                                singleResult.has(BODY_KEY)
                                                ? (JSONObject) Utility.getStringPropertyAsJSON(
                                                    singleResult,
                                                    BODY_KEY,
                                                    NON_JSON_RESPONSE_PROPERTY)
                                                : null,
                                                singleResult,
                                                batchResult,
                                                connection);
            }
        }
    } catch (JSONException e) {
        // defer the throwing of a JSONException to the graph object proxy
    }
    return null;
}
 
Example 16
Source File: LoginAty.java    From Huochexing12306 with Apache License 2.0 4 votes vote down vote up
@Override
public void handleMessage(Message msg) {
	switch (msg.what) {
	// 发送成功并收到返回信息
	case HttpUtil.MSG_SEND_SUCCESS:
		if (mLoginDlg != null){
			mLoginDlg.dismissAllowingStateLoss();
			mLoginDlg = null;
		}
		String responseMsg = msg.getData().getString("response");
		try {
			JSONObject jsonObj = new JSONObject(responseMsg);
			int resultCode = jsonObj.getInt("resultCode");
			if (resultCode == HttpUtil.MSG_SEND_FAIL) {
				// 用户名密码错误
				showMsg("用户名或密码错误,登录失败" + SF.FAIL);
			} else if (resultCode == HttpUtil.MSG_RECEIVE_EMPTY) {
				showMsg("此用户不存在" + SF.FAIL);
			} else if (resultCode == HttpUtil.MSG_RECEIVE_SUCCESS) {
				JSONObject subObj = jsonObj.getJSONObject("userInfo");
				// 保存用户信息
				userSP.setSessionCode(subObj.getString("sessionCode"));
				userSP.setUId(subObj.getInt("uid"));
				userSP.setUsername(subObj.getString("userName"));
				userSP.setNickName(subObj.getString("nickName"));
				String strIcon = subObj.getString("icon");
				if (!"".equals(strIcon)) {
					userSP.setHeadIcon(subObj.getString("icon"));
				}
				userSP.setSex(subObj.getString("sex"));
				userSP.setEmail(subObj.getString("email"));
				userSP.setPoint(subObj.getInt("point"));
				switch(msg.arg1){
				case 2:
					userSP.setThirdPartyLogin(true);
					break;
				default:
					userSP.setThirdPartyLogin(false);
				}
				
				MyApp.getInstance().mDefaultClearTextPwd = subObj.optString("cleartext_pwd");
				userSP.setLogin(true);
				userSP.setAutoLogin(true);
				showMsg("登录成功" + SF.SUCCESS);
				setResult(RESULT_OK);
				if (mIsFirstUseLogin){
					startActivity(new Intent(LoginAty.this, MainActivity.class));
				}else{
					LoginAty.this.finish();
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		break;
	// 发送失败
	case HttpUtil.MSG_SEND_FAIL:
		String errorMsg = "连接服务器失败";
		if (mLoginDlg != null){
			mLoginDlg.dismissAllowingStateLoss();
			mLoginDlg = null;
		}
		showMsg(errorMsg);
		break;
	}
}
 
Example 17
Source File: JSONParser.java    From 1Rramp-Android with MIT License 4 votes vote down vote up
private CommentModel parseCoreComment(JSONObject rootObject) {
  CommentModel comment = new CommentModel();
  try {
    //author
    String author = rootObject.getString("author");
    //permlink
    String permlink = rootObject.getString("permlink");
    //category
    String category = rootObject.getString("category");
    //parentAuthor
    String parentAuthor = rootObject.getString("parent_author");
    //parent permlink
    String parentPermlink = rootObject.getString("parent_permlink");
    //body
    String body = rootObject.getString("body");
    //createdAt
    String createdAt = rootObject.getString("created");
    //children
    int children = rootObject.getInt("children");
    //totalPayoutValue
    String totalPayoutValue = rootObject.getString("total_payout_value");
    //curator payout value
    String curatorPayoutValue = rootObject.getString("curator_payout_value");
    //root author
    String rootAuthor = rootObject.getString("root_author");
    //root permlink
    String rootPermlink = rootObject.getString("root_permlink");
    //pending payout value
    String pendingPayoutValue = rootObject.optString("pending_payout_value", "");
    //total pending payout value
    String totalPendingPayoutValue = rootObject.optString("total_pending_payout_value", "");
    String cashoutTime = rootObject.optString("cashout_time");
    //author reputation
    String autorReputation = rootObject.optString("author_reputation", "");
    comment.setBody(body);
    comment.setBody(body);
    comment.setAuthor(author);
    comment.setPermlink(permlink);
    comment.setCategory(category);
    comment.setParentAuthor(parentAuthor);
    comment.setParentPermlink(parentPermlink);
    comment.setCreatedAt(createdAt);
    comment.setChildren(children);
    comment.setTotalPayoutValue(totalPayoutValue);
    comment.setCuratorPayoutValue(curatorPayoutValue);
    comment.setPendingPayoutValue(pendingPayoutValue);
    comment.setTotalPendingPayoutValue(totalPendingPayoutValue);
    comment.setCashoutTime(cashoutTime);
  }
  catch (JSONException e) {
    Log.e("JsonParserException", e.toString());
  }
  return comment;
}
 
Example 18
Source File: ParserSet.java    From TvLauncher with Apache License 2.0 4 votes vote down vote up
@Override
public String parse(JSONObject data) throws DataParseException {
    return data.optString("newUserToken");
}
 
Example 19
Source File: DrawingBoardManager.java    From cidrawing with Apache License 2.0 4 votes vote down vote up
private String extractBoardId(JSONObject object) {
    return object.optString(DrawingBoardImpl.KEY_BOARD_ID);
}
 
Example 20
Source File: SonarQubeParser.java    From analysis-model with MIT License 2 votes vote down vote up
/**
 * Default parse for message.
 *
 * @param issue
 *         the object to parse.
 *
 * @return the message.
 */
private String parseMessage(final JSONObject issue) {
    return issue.optString(ISSUE_MESSAGE, "No message.");
}