Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject optJSONArray.

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:ru.rzn.myasoedov.vktest.dto.VKChat.java

@Override
public VKChat parse(JSONObject source) {
    try {/*from   w  ww  .  j  ava2  s  . com*/
        JSONObject message = source.getJSONObject("message");
        int chatId = message.getInt("chat_id");
        super.parse(message);
        id = chatId;
        preview = message.optString("body");
        date = message.optLong("date");
        photoUrl = message.optString("photo_50");
        JSONArray users = message.optJSONArray("chat_active");
        if (users != null) {
            this.users = new int[users.length()];
            for (int i = 0; i < this.users.length; i++) {
                this.users[i] = users.optInt(i);
            }
        }

    } catch (JSONException e) {
        return null;
    }
    return this;
}

From source file:com.funzio.pure2D.particles.nova.vo.NovaVO.java

public NovaVO(final JSONObject json) throws JSONException {
    mSource = json;/*  w w  w  .j  a  v  a2s  .c o  m*/

    version = json.optInt("version");
    name = json.optString("name");
    pool_size = json.optInt("pool_size");
    emitters = getEmitters(json.optJSONArray("emitters"));
    animators = getAnimators(json.optJSONArray("animators"));
    motion_trails = getMotionTrails(json.optJSONArray("motion_trails"));

    // make the maps
    if (emitters != null) {
        mEmitterMap = new HashMap<String, NovaEmitterVO>();
        for (final NovaEmitterVO vo : emitters) {
            mEmitterMap.put(vo.name, vo);
        }
    }

    if (animators != null) {
        mAnimatorMap = new HashMap<String, AnimatorVO>();
        for (final AnimatorVO vo : animators) {
            if (vo != null) {
                mAnimatorMap.put(vo.name, vo);
            }
        }
    }

    if (motion_trails != null) {
        mMotionTrailMap = new HashMap<String, MotionTrailVO>();
        for (final MotionTrailVO vo : motion_trails) {
            if (vo != null) {
                mMotionTrailMap.put(vo.name, vo);
            }
        }
    }
}

From source file:com.soomla.levelup.LevelUp.java

private static HashMap<String, JSONObject> getListFromWorlds(JSONObject model, String listName) {
    HashMap<String, JSONObject> resultHash = new HashMap<String, JSONObject>();

    HashMap<String, JSONObject> worldJSONs = getWorlds(model);

    for (JSONObject worldJSON : worldJSONs.values()) {
        JSONArray objectJSONs = worldJSON.optJSONArray(listName);
        if (objectJSONs != null) {
            for (int i = 0; i < objectJSONs.length(); i++) {
                JSONObject objectJSON = objectJSONs.optJSONObject(i);
                if (objectJSON != null) {
                    String objectId = objectJSON.optString("itemId");
                    if (!TextUtils.isEmpty(objectId)) {
                        resultHash.put(objectId, objectJSON);
                    }/* w  w  w  .  j a v a 2s. com*/
                }
            }
        }
    }

    return resultHash;
}

From source file:org.ESLM.Parser.JSONLessonParser.java

private void parseLesson() throws BadFormedJSONExerciseException {
    JSONTokener tokener = new JSONTokener(reader);
    JSONObject jsonLesson = new JSONObject(tokener);
    String title = jsonLesson.optString("title", "Untitled Lesson");
    JSONArray jsonExercises = jsonLesson.optJSONArray("exercises");
    Exercise[] exercises = parseExercises(jsonExercises);
    parsedLesson = new Lesson(title, exercises);
}

From source file:org.eclipse.orion.server.git.GitFileDecorator.java

@Override
public void addAtributesFor(HttpServletRequest request, URI resource, JSONObject representation) {
    String requestPath = request.getServletPath()
            + (request.getPathInfo() == null ? "" : request.getPathInfo());
    IPath targetPath = new Path(requestPath);
    if (targetPath.segmentCount() <= 1)
        return;//w ww.  j a  v a  2s.  c  om
    String servlet = request.getServletPath();
    if (!"/file".equals(servlet) && !"/workspace".equals(servlet)) //$NON-NLS-1$ //$NON-NLS-2$
        return;

    boolean isWorkspace = ("/workspace".equals(servlet)); //$NON-NLS-1$

    try {
        if (isWorkspace && Method.POST.equals(Method.fromString(request.getMethod()))) {
            String contentLocation = representation.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

            // initialize a new git repository on project creation if specified by configuration
            initGitRepository(request, targetPath, representation);
            addGitLinks(request, new URI(contentLocation), representation);
            return;
        }

        if (isWorkspace && Method.GET.equals(Method.fromString(request.getMethod()))) {
            JSONArray children = representation.optJSONArray(ProtocolConstants.KEY_CHILDREN);
            if (children != null) {
                for (int i = 0; i < children.length(); i++) {
                    JSONObject child = children.getJSONObject(i);
                    String location = child.getString(ProtocolConstants.KEY_LOCATION);
                    addGitLinks(request, new URI(location), child);
                }
            }
            return;
        }

        if (!isWorkspace && Method.GET.equals(Method.fromString(request.getMethod()))) {
            //compute all git properties in advance because it will be same for all children
            Repository db = repositoryForPath(request, new Path(resource.getPath()));
            URI cloneLocation = BaseToCloneConverter.getCloneLocation(resource, BaseToCloneConverter.FILE);
            String branch = db == null ? null : db.getBranch();
            Remote defaultRemote = db == null ? null
                    : new Remote(cloneLocation, db, Constants.DEFAULT_REMOTE_NAME);
            RemoteBranch defaultRemoteBranch = db == null ? null
                    : new RemoteBranch(cloneLocation, db, defaultRemote, branch);
            addGitLinks(request, resource, representation, cloneLocation, db, defaultRemoteBranch, branch);

            JSONArray children = representation.optJSONArray(ProtocolConstants.KEY_CHILDREN);
            if (children != null) {
                for (int i = 0; i < children.length(); i++) {
                    JSONObject child = children.getJSONObject(i);
                    String location = child.getString(ProtocolConstants.KEY_LOCATION);
                    if (db != null) {
                        // if parent was a git repository we can reuse information computed above
                        addGitLinks(request, new URI(location), child, cloneLocation, db, defaultRemoteBranch,
                                branch);
                    } else {
                        //maybe the child is the root of a git repository
                        addGitLinks(request, new URI(location), child);
                    }
                }
            }
        }
    } catch (Exception e) {
        // log and continue
        LogHelper.log(e);
    }
}

From source file:com.apecat.shoppingadvisor.scan.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;// w w w .j ava2s  . c o  m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e);
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:kr.ac.cau.mecs.cass.processor.CASSensorProcessor.java

@Override
public Signal process(Signal signal) {
    Signal resignal = new Signal();

    resignal.setReceiver(signal.getSender());
    resignal.setSender("CASS");
    resignal.setAction(new Action(Action.ACT_SENSOR));

    CAECalculator calc = new CAECalculator();

    if (currentUser != null) {
        JSONObject _jobj = (JSONObject) signal.getPayload().getPayload().getData();

        JSONArray jsensors = _jobj.optJSONArray("sensors");

        List<SensorEntity> sensors = new ArrayList<>();

        for (int i = 0; i < jsensors.length(); i++) {
            sensors.add(SensorEntity.fromJSONObject(jsensors.getJSONObject(i)));
        }// ww w  .  ja  v  a 2 s .  c om

        List<ActionScoreEntity> scores = new ArrayList<>();
        for (DBCAUEntity cau : currentUser.getCaus()) {
            for (DBActionEntity action : cau.getActions()) {
                scores.add(calc.calculateActionScore(cau, action, sensors));
            }
        }

        Collections.sort(scores);
        Collections.reverse(scores);//decending order...

        JSONObject jobj = new JSONObject();
        JSONArray jarr = new JSONArray();

        for (ActionScoreEntity score : scores) {
            jarr.put(score.toJSONObject());
        }
        jobj.put("scores", jarr);

        resignal.setPayload(new Payload(new JSONObjectPayload(jobj)));

    } else {
        setGenericMessage(resignal, "invalid credential");
    }

    return resignal;
}

From source file:com.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/users/#get_users_feed
 *//*from w  w  w.ja va  2  s  .c o  m*/
public static ArrayList<Media> getSelfFeed(Integer count, Integer minId, Integer maxId, String accessToken)
        throws IOException, JSONException {
    Params params = new Params("/users/self/feed");
    params.put("count", count);
    params.put("min_id", minId);
    params.put("max_id", maxId);
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(Api.API_BASE_URL, params, Network.Request.GET);
    JSONArray mediaJSONArray = rootJSON.optJSONArray("data");
    ArrayList<Media> medias = new ArrayList<>();
    for (int i = 0; i < mediaJSONArray.length(); i++) {
        JSONObject mediaJSON = (JSONObject) mediaJSONArray.get(i);
        medias.add(Media.fromJSON(mediaJSON));
    }
    return medias;
}

From source file:com.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/users/#get_users_media_recent
 * @param minTimestamp is a UNIX timestamp
 * @param maxTimestamp is a UNIX timestamp
 *///from   ww w .j  av  a  2s.c  om
public static ArrayList<Media> getUserMediaRecent(String userId, Integer count, Integer minId, Integer maxId,
        Integer minTimestamp, Integer maxTimestamp, String accessToken) throws IOException, JSONException {
    Params params = new Params("/users/" + userId + "/media/recent");
    params.put("count", count);
    params.put("min_id", minId);
    params.put("max_id", maxId);
    params.put("min_timestamp", minTimestamp);
    params.put("max_timestamp", maxTimestamp);
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(API_BASE_URL, params, Network.Request.GET);
    JSONArray mediaJSONArray = rootJSON.optJSONArray("data");
    ArrayList<Media> medias = new ArrayList<>();
    for (int i = 0; i < mediaJSONArray.length(); i++) {
        JSONObject mediaJSON = (JSONObject) mediaJSONArray.get(i);
        medias.add(Media.fromJSON(mediaJSON));
    }
    return medias;
}

From source file:com.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/users/#get_users_feed_liked
 *///from w  w  w  . j a  v a2s  . co m
public static ArrayList<Media> getSelfMediaLiked(Integer count, Integer maxLikeId, String accessToken)
        throws IOException, JSONException {
    Params params = new Params("/users/self/media/liked");
    params.put("count", count);
    params.put("max_like_id", maxLikeId);
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(API_BASE_URL, params, Network.Request.GET);
    JSONArray mediaJSONArray = rootJSON.optJSONArray("data");
    ArrayList<Media> medias = new ArrayList<>();
    for (int i = 0; i < mediaJSONArray.length(); i++) {
        JSONObject mediaJSON = (JSONObject) mediaJSONArray.get(i);
        medias.add(Media.fromJSON(mediaJSON));
    }
    return medias;
}