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

The following examples show how to use org.json.JSONObject#optJSONObject() . These examples are extracted from open source projects. 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
private void doWatchRemove(JSONObject watchRemoveSpec) throws Exception {
  Status error = null;
  JSONObject cause = watchRemoveSpec.optJSONObject("cause");
  if (cause != null) {
    int code = cause.optInt("code");
    if (code != 0) {
      error = Status.fromCodeValue(code);
    }
  }
  List<Integer> targetIds = parseIntList(watchRemoveSpec.getJSONArray("targetIds"));
  WatchTargetChange change =
      new WatchTargetChange(
          WatchTargetChangeType.Removed, targetIds, WatchStream.EMPTY_RESUME_TOKEN, error);
  writeWatchChange(change, SnapshotVersion.NONE);
  // Unlike web, the MockDatastore detects a watch removal with cause and will remove active
  // targets
}
 
Example 2
Source Project: swift-js-transpiler   File: TypeLoader.java    License: MIT License 6 votes vote down vote up
static private FunctionDefinition parseFunction(String name, JSONObject src, boolean isTopLevel, Cache cache, SwiftParser.Top_levelContext topLevel) {

        List<String> parameterExternalNames = new ArrayList<String>();
        List<Instance> parameterTypes = new ArrayList<Instance>();
        if(src.optJSONArray("parameters") != null) {
            for(int i = 0; i < src.optJSONArray("parameters").length(); i++) {
                JSONObject parameter = src.optJSONArray("parameters").optJSONObject(i);
                parameterExternalNames.add(parameter.optString("externalName"));
                parameterTypes.add(parseType(parameter.optString("type"), cache, topLevel));
            }
        }

        FunctionDefinition definition = new FunctionDefinition(name, parameterExternalNames, parameterTypes, 0, parseType(src.optString("type"), cache, topLevel), null);

        if(src.optJSONObject("codeReplacement") != null && isTopLevel) {
            definition.codeReplacement = new HashMap<String, String>();
            for(int i = 0; i < src.optJSONObject("codeReplacement").names().length(); i++) {
                String language = src.optJSONObject("codeReplacement").names().optString(i);
                definition.codeReplacement.put(language, src.optJSONObject("codeReplacement").optString(language));
            }
        }

        return definition;
    }
 
Example 3
Source Project: Klyph   File: SearchPageRequest.java    License: MIT License 6 votes vote down vote up
@Override
public List<GraphObject> handleResult(JSONArray result)
{
	List<GraphObject> list = new ArrayList<GraphObject>();
	
	int n = result.length();
	for (int i = 0; i < n; i++)
	{
		Page page = new Page();
		JSONObject json = result.optJSONObject(i);
		page.setPage_id(json.optString("id"));
		page.setName(json.optString("name"));
		page.setType(json.optString("category"));
		
		JSONObject pic = json.optJSONObject("picture");
		JSONObject data = pic.optJSONObject("data");
		page.setPic(data.optString("url"));
		list.add(page);
	}
	
	setHasMoreData(false);
	
	return list;
}
 
Example 4
Source Project: MaterialQQLite   File: SetSignResult.java    License: 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");
		json = json.optJSONObject("result");
		m_nResult = json.optInt("result");
		
		return true;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return false;
}
 
Example 5
Source Project: talk-android   File: RoomDeserializer.java    License: MIT License 6 votes vote down vote up
@Override
public Room deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Room room;
    GsonProvider.Builder builder = new GsonProvider.Builder();
    Gson gson = builder.addDeserializationExclusionStrategy("prefs")
            .setDateAdapter()
            .create();
    try {
        JSONObject jsonObj = new JSONObject(json.toString());
        room = gson.fromJson(json, Room.class);
        boolean isMute = false;
        if (jsonObj.optJSONObject("prefs") != null) {
            isMute = jsonObj.optJSONObject("prefs").optBoolean("isMute", false);
        }
        room.setIsMute(isMute);
    } catch (Exception e) {
        return null;
    }
    return room;
}
 
Example 6
Source Project: letv   File: LetvBaseParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isHotPointTokenInvalid(JSONObject object) {
    boolean isInvalid = false;
    JSONObject body = object.optJSONObject("body");
    if (!isNull(body) && TextUtils.equals(body.optString("code"), "403")) {
        isInvalid = true;
    }
    LogInfo.log("isHotPointTokenInvalid", "isInvalid : " + isInvalid);
    return isInvalid;
}
 
Example 7
Source Project: letv   File: LetvMobileParser.java    License: Apache License 2.0 5 votes vote down vote up
protected JSONObject getData(String data) throws Exception {
    if (this.status != 1 && this.status != 6) {
        return null;
    }
    JSONObject object = new JSONObject(data);
    if (isNull(object)) {
        return null;
    }
    JSONObject bodyJson = object.optJSONObject("body");
    if (isNull(bodyJson) || bodyJson.toString().equals("{}")) {
        return null;
    }
    return bodyJson;
}
 
Example 8
public static AnimationsOptions parse(JSONObject json) {
    AnimationsOptions options = new AnimationsOptions();
    if (json == null) return options;

    options.push = NestedAnimationsOptions.parse(json.optJSONObject("push"));
    options.pop = NestedAnimationsOptions.parse(json.optJSONObject("pop"));
    options.setStackRoot = NestedAnimationsOptions.parse(json.optJSONObject("setStackRoot"));
    options.setRoot = new AnimationOptions(json.optJSONObject("setRoot"));
    options.showModal = new AnimationOptions(json.optJSONObject("showModal"));
    options.dismissModal = new AnimationOptions(json.optJSONObject("dismissModal"));

    return options;
}
 
Example 9
/**
 * Create a PayPalPaymentResource from a jsonString. Checks for keys associated with
 * Single Payment and Billing Agreement flows.
 *
 * @param jsonString a valid JSON string representing the payment resource
 * @return a PayPal payment resource
 * @throws JSONException
 */
public static PayPalPaymentResource fromJson(String jsonString) throws JSONException {
    JSONObject json = new JSONObject(jsonString);

    PayPalPaymentResource payPalPaymentResource = new PayPalPaymentResource();
    JSONObject redirectJson = json.optJSONObject(PAYMENT_RESOURCE_KEY);
    if(redirectJson != null) {
        payPalPaymentResource.redirectUrl(Json.optString(redirectJson, REDIRECT_URL_KEY, ""));
    } else {
        redirectJson = json.optJSONObject(AGREEMENT_SETUP_KEY);
        payPalPaymentResource.redirectUrl(Json.optString(redirectJson, APPROVAL_URL_KEY, ""));
    }
    return payPalPaymentResource;
}
 
Example 10
@JavascriptInterface
public void setConfig(String jsParams) {
    try {
        JSONObject json = new JSONObject(jsParams);
        JSONObject payStatus = json.optJSONObject("msg");
        payDisabled = payStatus.optBoolean("payDisabled");
        //todo
    } catch (JSONException e) {

    }
}
 
Example 11
Source Project: letv   File: LetvBaseParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isCreditTokenInvalid(JSONObject object) {
    JSONObject body = object.optJSONObject("body");
    if (isNull(body) || !TextUtils.equals(body.optString("code"), "201")) {
        return false;
    }
    return true;
}
 
Example 12
@Nullable
public static Action instantiate(JSONObject object) {
    try {
        String type = object.getString("type");
        JSONObject data = object.optJSONObject("data");
        Class clazz = Class.forName(type);
        return ((Action) clazz.newInstance()).fromJSON(data != null ? data.toString() : "");
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | JSONException e) {
        log.error("Unhandled exception", e);
    }
    return null;
}
 
Example 13
Source Project: cordova-social-vk   File: VKApiPost.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fills a Post instance from JSONObject.
 */
public VKApiPost parse(JSONObject source) throws JSONException {
    id = source.optInt("id");
    to_id = source.optInt("to_id");
    from_id = source.optInt("from_id");
    date = source.optLong("date");
    text = source.optString("text");
    reply_owner_id = source.optInt("reply_owner_id");
    reply_post_id = source.optInt("reply_post_id");
    friends_only = ParseUtils.parseBoolean(source, "friends_only");
    JSONObject comments = source.optJSONObject("comments");
    if(comments != null) {
        comments_count = comments.optInt("count");
        can_post_comment = ParseUtils.parseBoolean(comments, "can_post");
    }
    JSONObject likes = source.optJSONObject("likes");
    if(likes != null) {
        likes_count = likes.optInt("count");
        user_likes = ParseUtils.parseBoolean(likes, "user_likes");
        can_like = ParseUtils.parseBoolean(likes, "can_like");
        can_publish = ParseUtils.parseBoolean(likes, "can_publish");
    }
    JSONObject reposts = source.optJSONObject("reposts");
    if(reposts != null) {
        reposts_count = reposts.optInt("count");
        user_reposted = ParseUtils.parseBoolean(reposts, "user_reposted");
    }
    post_type = source.optString("post_type");
    attachments.fill(source.optJSONArray("attachments"));
    JSONObject geo = source.optJSONObject("geo");
    if(geo != null) {
        this.geo = new VKApiPlace().parse(geo);
    }
    signer_id = source.optInt("signer_id");
    copy_history = new VKList<VKApiPost>(source.optJSONArray("copy_history"), VKApiPost.class);
    return this;
}
 
Example 14
Source Project: letv   File: VideoBean.java    License: Apache License 2.0 4 votes vote down vote up
public static VideoBean parse(JSONObject obj) {
    VideoBean video = new VideoBean();
    video.vid = obj.optLong("vid");
    video.pid = obj.optLong("pid");
    video.cid = obj.optInt("cid");
    video.zid = obj.optString(PlayConstant.ZID);
    video.nameCn = obj.optString("nameCn");
    video.subTitle = obj.optString("subTitle");
    video.singer = obj.optString("singer");
    video.releaseDate = obj.optString("releaseDate");
    video.style = obj.optString("style");
    video.playMark = obj.optString("playMark");
    video.vtypeFlag = obj.optString("vtypeFlag");
    video.guest = obj.optString("guest");
    video.type = obj.optInt("type");
    video.btime = obj.optLong(DownloadVideoTable.COLUMN_BTIME);
    video.etime = obj.optLong(DownloadVideoTable.COLUMN_ETIME);
    video.duration = obj.optLong(DownloadVideoTable.COLUMN_DURATION);
    video.mid = obj.optString("mid");
    video.episode = obj.optString("episode");
    video.porder = obj.optString("porder");
    video.pay = obj.optInt("pay");
    video.albumPay = obj.optInt("album_pay");
    video.download = obj.optInt("download");
    JSONObject picAll = obj.optJSONObject("picAll");
    if (picAll != null) {
        video.pic320_200 = picAll.optString("320*200");
        video.pic120_90 = picAll.optString("120*90");
    }
    if (!TextUtils.isEmpty(obj.optString("mobilePic"))) {
        video.pic320_200 = obj.optString("mobilePic");
    }
    video.play = obj.optInt("play");
    video.openby = obj.optInt("openby");
    video.jump = obj.optInt("jump");
    video.jumptype = obj.optString("jumptype");
    video.jumpLink = obj.optString("jumplink");
    video.isDanmaku = obj.optInt("isDanmaku");
    video.brList = obj.optString("brList");
    video.videoTypeKey = obj.optString(DownloadVideoTable.COLUMN_VIDEOTYPEKEY);
    video.videoType = obj.optString(PlayConstant.VIDEO_TYPE);
    video.videoTypeName = obj.optString("videoTypeName");
    video.controlAreas = obj.optString("controlAreas");
    video.disableType = obj.optInt("disableType");
    video.cornerMark = obj.optString("cornerMark");
    video.playCount = obj.optLong("playCount");
    video.score = obj.optString("score");
    video.director = obj.optString("director");
    video.starring = obj.optString("starring");
    video.reid = obj.optString("reid");
    video.bucket = obj.optString("bucket");
    video.area = obj.optString("area");
    video.isRec = obj.optBoolean("is_rec", false);
    video.dataArea = obj.optString("dataArea");
    video.subCategory = obj.optString("subCategory");
    video.title = obj.optString("title");
    video.pidname = obj.optString("pidname");
    video.subname = obj.optString("subname");
    video.pidsubtitle = obj.optString("pidsubtitle");
    video.picHT = obj.optString("picHT");
    video.picST = obj.optString("picST");
    video.at = obj.optInt(PushDataParser.AT);
    video.createYear = obj.optString("createYear");
    video.createMonth = obj.optString("createMonth");
    JSONArray jsonFocusrray = obj.optJSONArray("watchingFocus");
    if (jsonFocusrray != null && jsonFocusrray.length() > 0) {
        int len = jsonFocusrray.length();
        for (int j = 0; j < len; j++) {
            JSONObject jsonFocusObj = jsonFocusrray.optJSONObject(j);
            WatchingFocusItem mWatchingFocusItem = new WatchingFocusItem();
            mWatchingFocusItem.desc = jsonFocusObj.optString(SocialConstants.PARAM_APP_DESC);
            mWatchingFocusItem.id = jsonFocusObj.optInt("id");
            mWatchingFocusItem.picUrl = jsonFocusObj.optString(DownloadBaseColumns.COLUMN_PIC);
            mWatchingFocusItem.timeDot = jsonFocusObj.optString("time");
            video.watchingFocusList.add(mWatchingFocusItem);
        }
    }
    return video;
}
 
Example 15
@Override
protected Response<ArrayList<Commentator>> parseNetworkResponse(NetworkResponse response) {

    try {
        //获取到所有的数据
        String jsonStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        JSONObject resultJson = new JSONObject(jsonStr);
        String allThreadId = resultJson.getString("response").replace("[", "").replace
                ("]", "").replace("\"", "");
        String[] threadIds = allThreadId.split("\\,");

        callBack.loadFinish(resultJson.optJSONObject("thread").optString("thread_id"));

        if (TextUtils.isEmpty(threadIds[0])) {
            return Response.success(new ArrayList<Commentator>(), HttpHeaderParser
                    .parseCacheHeaders(response));
        } else {

            //然后根据thread_id再去获得对应的评论和作者信息
            JSONObject parentPostsJson = resultJson.getJSONObject("parentPosts");
            //找出热门评论
            String hotPosts = resultJson.getString("hotPosts").replace("[", "").replace
                    ("]", "").replace("\"", "");
            String[] allHotPosts = hotPosts.split("\\,");

            ArrayList<Commentator> commentators = new ArrayList<>();
            List<String> allHotPostsArray = Arrays.asList(allHotPosts);

            for (String threadId : threadIds) {
                Commentator commentator = new Commentator();
                JSONObject threadObject = parentPostsJson.getJSONObject(threadId);

                //解析评论,打上TAG
                if (allHotPostsArray.contains(threadId)) {
                    commentator.setTag(Commentator.TAG_HOT);
                } else {
                    commentator.setTag(Commentator.TAG_NORMAL);
                }

                commentator.setPost_id(threadObject.optString("post_id"));
                commentator.setParent_id(threadObject.optString("parent_id"));

                String parentsString = threadObject.optString("parents").replace("[", "").replace
                        ("]", "").replace("\"", "");

                String[] parents = parentsString.split("\\,");
                commentator.setParents(parents);

                //如果第一个数据为空,则只有一层
                if (TextUtil.isNull(parents[0])) {
                    commentator.setFloorNum(1);
                } else {
                    commentator.setFloorNum(parents.length + 1);
                }

                commentator.setMessage(threadObject.optString("message"));
                commentator.setCreated_at(threadObject.optString("created_at"));
                JSONObject authorObject = threadObject.optJSONObject("author");
                commentator.setName(authorObject.optString("name"));
                commentator.setAvatar_url(authorObject.optString("avatar_url"));
                commentator.setType(Commentator.TYPE_NORMAL);
                commentators.add(commentator);
            }

            return Response.success(commentators, HttpHeaderParser.parseCacheHeaders(response));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return Response.error(new ParseError(e));
    }
}
 
Example 16
public static boolean cacheDisabled(@Nullable JSONObject config) {
  return (config != null && config.optJSONObject("disableCache") != null) &&
    Objects.requireNonNull(config.optJSONObject("disableCache")).optBoolean("bool", false);
}
 
Example 17
Source Project: JianDanRxJava   File: CommentListParser.java    License: Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public ArrayList<Commentator> parse(Response response) {

    if (!response.isSuccessful())
        return null;


    try {
        //获取到所有的数据
        String jsonStr = response.body().string();
        JSONObject resultJson = new JSONObject(jsonStr);
        String allThreadId = resultJson.getString("response").replace("[", "").replace
                ("]", "").replace("\"", "");
        String[] threadIds = allThreadId.split("\\,");

        mCallBack.loadFinish(resultJson.optJSONObject("thread").optString("thread_id"));

        if (TextUtils.isEmpty(threadIds[0])) {
            return new ArrayList<>();
        } else {

            //然后根据thread_id再去获得对应的评论和作者信息
            JSONObject parentPostsJson = resultJson.getJSONObject("parentPosts");
            //找出热门评论
            String hotPosts = resultJson.getString("hotPosts").replace("[", "").replace
                    ("]", "").replace("\"", "");
            String[] allHotPosts = hotPosts.split("\\,");

            ArrayList<Commentator> commentators = new ArrayList<>();
            List<String> allHotPostsArray = Arrays.asList(allHotPosts);

            for (String threadId : threadIds) {
                Commentator commentator = new Commentator();
                JSONObject threadObject = parentPostsJson.getJSONObject(threadId);

                //解析评论,打上TAG
                if (allHotPostsArray.contains(threadId)) {
                    commentator.setTag(Commentator.TAG_HOT);
                } else {
                    commentator.setTag(Commentator.TAG_NORMAL);
                }

                commentator.setPost_id(threadObject.optString("post_id"));
                commentator.setParent_id(threadObject.optString("parent_id"));

                String parentsString = threadObject.optString("parents").replace("[", "").replace
                        ("]", "").replace("\"", "");

                String[] parents = parentsString.split("\\,");
                commentator.setParents(parents);

                //如果第一个数据为空,则只有一层
                if (TextUtil.isNull(parents[0])) {
                    commentator.setFloorNum(1);
                } else {
                    commentator.setFloorNum(parents.length + 1);
                }

                commentator.setMessage(threadObject.optString("message"));
                commentator.setCreated_at(threadObject.optString("created_at"));
                JSONObject authorObject = threadObject.optJSONObject("author");
                commentator.setName(authorObject.optString("name"));
                commentator.setAvatar_url(authorObject.optString("avatar_url"));
                commentator.setType(Commentator.TYPE_NORMAL);
                commentators.add(commentator);
            }

            return commentators;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 18
Source Project: cordova-social-vk   File: VKApiVideo.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Fills a Video instance from JSONObject.
 */
public VKApiVideo parse(JSONObject from) {
    id = from.optInt("id");
    owner_id = from.optInt("owner_id");
    title = from.optString("title");
    description = from.optString("description");
    duration = from.optInt("duration");
    link = from.optString("link");
    date = from.optLong("date");
    views = from.optInt("views");
    comments = from.optInt("comments");
    player = from.optString("player");
    access_key = from.optString("access_key");
    album_id = from.optInt("album_id");

    JSONObject likes = from.optJSONObject("likes");
    if(likes != null) {
        this.likes = likes.optInt("count");
        user_likes = parseBoolean(likes, "user_likes");
    }
    can_comment = parseBoolean(from, "can_comment");
    can_repost = parseBoolean(from, "can_repost");
    repeat = parseBoolean(from, "repeat");

    privacy_view = VKPrivacy.parsePrivacy(from.optJSONObject("privacy_view"));
    privacy_comment = VKPrivacy.parsePrivacy(from.optJSONObject("privacy_comment"));

    JSONObject files = from.optJSONObject("files");
    if(files != null) {
        mp4_240 = files.optString("mp4_240");
        mp4_360 = files.optString("mp4_360");
        mp4_480 = files.optString("mp4_480");
        mp4_720 = files.optString("mp4_720");
        mp4_1080 = files.optString("mp4_1080");
        external = files.optString("external");
    }

    photo_130 = from.optString("photo_130");
    if(!TextUtils.isEmpty(photo_130)) {
        photo.add(VKApiPhotoSize.create(photo_130, 130));
    }

    photo_320 = from.optString("photo_320");
    if(!TextUtils.isEmpty(photo_320)) {
        photo.add(VKApiPhotoSize.create(photo_320, 320));
    }

    photo_640 = from.optString("photo_640");
    if(!TextUtils.isEmpty(photo_640)) {
        photo.add(VKApiPhotoSize.create(photo_640, 640));
    }
    return this;
}
 
Example 19
private Intent parseIntent(
    JSONObject jsonIntent
) throws JSONException {

    Intent intent = new Intent();
    
    String activityClass = jsonIntent.optString(
        "activityClass", 
        this.cordova.getActivity().getClass().getName());
    String activityPackage = jsonIntent.optString(
        "activityPackage", 
        this.cordova.getActivity().getPackageName());
    intent.setClassName(activityPackage, activityClass);

    String action = jsonIntent.optString("action", Intent.ACTION_VIEW);
    if (action.indexOf('.') < 0) {
        action = activityPackage + '.' + action;
    }
    Log.i(TAG, "Creating new intent with action: " + action);
    intent.setAction(action);

    int flags = jsonIntent.optInt("flags", Intent.FLAG_ACTIVITY_NEW_TASK + Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setFlags(flags); // TODO: Support passing different flags

    JSONArray jsonCategories = jsonIntent.optJSONArray("categories");
    if (jsonCategories != null) {
        int count = jsonCategories.length();
        for (int i = 0; i < count; ++i) {
            String category = jsonCategories.getString(i);
            if (category.indexOf('.') < 0) {
                category = activityPackage + '.' + category;
            }
            intent.addCategory(category);
        }
    }

    String data = jsonIntent.optString("data");
    if (data.length() > 0) {
        intent.setData(Uri.parse(data));
    }

    JSONObject extras = jsonIntent.optJSONObject("extras");
    if (extras != null) {
        Iterator<String> keys = extras.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            Object value = extras.get(key);
            if (value != null) {
                if (key.indexOf('.') < 0) {
                    key = activityPackage + "." + key;                            
                }
                if (value instanceof Boolean) {
                    intent.putExtra(key, (Boolean)value);
                } 
                else if (value instanceof Integer) {
                    intent.putExtra(key, (Integer)value);
                }
                else if (value instanceof Long) {
                    intent.putExtra(key, (Long)value);
                } 
                else if (value instanceof Float) {
                    intent.putExtra(key, (Float)value);
                } 
                else if (value instanceof Double) {
                    intent.putExtra(key, (Double)value);
                } 
                else {
                    intent.putExtra(key, value.toString());
                }
            }
        }
    }
    return intent;
}
 
Example 20
Source Project: letv   File: CommonParser.java    License: Apache License 2.0 4 votes vote down vote up
protected JSONObject getJSONObject(JSONObject object, String name) {
    return object.optJSONObject(name);
}