Example usage for org.json.simple JSONArray size

List of usage examples for org.json.simple JSONArray size

Introduction

In this page you can find the example usage for org.json.simple JSONArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:com.healthcit.analytics.utils.ExcelExportUtils.java

@SuppressWarnings("unchecked")
public static void streamVisualizationDataAsExcelFormat(OutputStream out, JSONObject data) {
    // Get the array of columns
    JSONArray jsonColumnArray = (JSONArray) data.get(COLUMNS_JSON_KEY);

    String[] excelColumnArray = new String[jsonColumnArray.size()];

    for (int index = 0; index < excelColumnArray.length; ++index) {
        excelColumnArray[index] = (String) ((JSONObject) jsonColumnArray.get(index)).get(LABEL_JSON_KEY);
    }//from   w w  w.  j a  v a2  s . co m

    // Get the array of rows
    JSONArray jsonRowArray = (JSONArray) data.get(ROWS_JSON_KEY);

    JSONArray excelRowArray = new JSONArray();

    Iterator<JSONObject> jsonRowIterator = jsonRowArray.iterator();

    while (jsonRowIterator.hasNext()) {
        JSONArray rowCell = (JSONArray) jsonRowIterator.next().get(ROWCELL_JSON_KEY);

        JSONObject excelRowObj = new JSONObject();

        for (int index = 0; index < rowCell.size(); ++index) {

            excelRowObj.put(excelColumnArray[index],
                    ((JSONObject) rowCell.get(index)).get(ROWCELLVALUE_JSON_KEY));
        }

        excelRowArray.add(excelRowObj);
    }

    // build the Excel outputstream
    Json2Excel.build(out, excelRowArray.toJSONString(), excelColumnArray);
}

From source file:com.avatarproject.core.storage.UserCache.java

/**
 * Gets a UUID of a user from the custom UserCache.
 * @param playername String name of the player to get.
 * @return UUID of the player.//from   w  w w . j  av a  2s .  c  om
 */
public static UUID getUser(String playername) {
    JSONArray array = getUserCache();
    try {
        for (int n = 0; n < array.size(); n++) { //Loop through all the objects in the array.
            JSONObject object = (JSONObject) array.get(n);
            if (String.valueOf(object.get("name")).equalsIgnoreCase(playername)) {
                return UUID.fromString(String.valueOf(object.get("id")));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:iracing.webapi.SeasonTimeTrialStandingsParser.java

public static SeasonTimeTrialStandings parse(String json) {
    JSONParser parser = new JSONParser();
    SeasonTimeTrialStandings output = null;
    try {//from  ww w  . j a  v  a 2 s  .c  o m
        JSONObject root = (JSONObject) parser.parse(json);
        Object o = root.get("d");
        if (o instanceof JSONObject) {
            JSONObject d = (JSONObject) o;
            output = new SeasonTimeTrialStandings();
            String s = getString(d, "5");
            output.setApiUserRow(Integer.parseInt(s));
            output.setTotalRecords(getLong(d, "18"));
            JSONArray arrayRoot = (JSONArray) d.get("r");
            List<SeasonTimeTrialStanding> standings = new ArrayList<SeasonTimeTrialStanding>();
            for (int i = 0; i < arrayRoot.size(); i++) {
                JSONObject r = (JSONObject) arrayRoot.get(i);
                SeasonTimeTrialStanding standing = new SeasonTimeTrialStanding();
                standing.setDroppedWeeks(getInt(r, "1"));
                standing.setClubName(getString(r, "2", true));
                o = r.get("3");
                if (o instanceof Double) {
                    standing.setTotalPoints((Double) o);
                } else if (o instanceof Long) {
                    standing.setTotalPoints(Double.parseDouble(String.valueOf(o)));
                }
                standing.setLicenseSubLevel(getString(r, "4"));
                standing.setMaxLicenseLevel(getInt(r, "6"));
                standing.setRank(getInt(r, "7"));
                standing.setDivision(getInt(r, "9"));
                standing.setDriverName(getString(r, "10", true));
                standing.setDriverCustomerId(getLong(r, "12"));
                standing.setTotalStarts(getInt(r, "14"));
                standing.setClubId(getInt(r, "15"));
                standing.setWeeksCounted(getInt(r, "17"));
                standing.setTotalWins(getInt(r, "19"));
                standing.setPosition(getInt(r, "20"));
                standings.add(standing);
            }
            output.setStandings(standings);
        }
    } catch (ParseException ex) {
        Logger.getLogger(SeasonTimeTrialStandingsParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:eu.riscoss.rdc.GithubAPI_Test.java

/**
 * GIT API Test method //w  ww . j  ava 2 s  .c o  m
 * @param req
 * @return
 */
static JSONArray gitJSONGetter() {
    String json = "";
    //String repository = values.get("repository");

    String owner = "RISCOSS/";
    //String repo = "riscoss-analyser/";
    String repo = "riscoss-data-collector/";

    String r = owner + repo;

    String req;
    req = r + "commits";

    //NST: needs some time to be calculated. 1st time it returns Status 202!
    req = r + "stats/contributors"; //NST single contributors with weekly efforts: w:week, a:add, d:del, c:#commits

    //https://developer.github.com/v3/repos/statistics/#commit-activity
    req = r + "stats/commit_activity";//NST data per week (1y):  The days array is a group of commits per day, starting on Sunday.

    req = r + "collaborators"; //needs authorization! Error 401

    req = r + "events"; //committs and other events. Attention: max 10x30 events, max 90days!

    req = r + "issues?state=all"; //all issues. Of interest: state=open, closed, 

    //      req = r + "stats/participation";//NST  weekly commit count

    //req = r + "stats/code_frequency";  //NST: week,  number of additions, number of deletions per week

    //HttpGet( "https://api.github.com/rate_limit");  //rate limit is 60 requests per hour!!
    /**
     * TODO:
     * participation: week list, analysis value
     * issues open, issues closed today status
     *  
     */

    HttpGet get = new HttpGet("https://api.github.com/repos/" + req);
    //get = new HttpGet( "https://api.github.com/rate_limit");

    //only for getting the License
    //get.setHeader("Accept", "application/vnd.github.drax-preview+json");

    HttpResponse response;
    try {
        response = client.execute(get);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            json = EntityUtils.toString(entity);

        } else if (response.getStatusLine().getStatusCode() == 202) {
            System.err.println("WARNING 202 Accept: Computing....try again in some seconds.");
            return null;
        } else {
            // something has gone wrong...
            System.err.println(response.getStatusLine().getStatusCode());
            System.err.println(response.getStatusLine().toString());
            return null;
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    System.out.println("****JSON****\n" + json + "\n************");

    try {
        JSONAware jv = (JSONAware) new JSONParser().parse(json);

        if (jv instanceof JSONObject) {
            JSONObject jo = (JSONObject) jv;
            System.out.println("JO: ");
            for (Object o : jo.entrySet()) {
                System.out.println("\t" + o);
            }

        }

        if (jv instanceof JSONArray) {
            JSONArray ja = (JSONArray) jv;

            int size = ja.size();
            System.out.println("JA Size = " + size);
            for (Object o : ja) {
                if (o instanceof JSONObject) {
                    JSONObject jo = (JSONObject) o;
                    System.out.println("JA Object:");
                    for (Object o2 : jo.entrySet()) {
                        System.out.println("\t" + o2);
                    }
                } else {
                    System.out.println("JA Array: " + (JSONArray) o);
                }
            }
            return ja;
        }

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:iracing.webapi.TimeTrialResultStandingsParser.java

public static TimeTrialResultStandings parse(String json) {
    TimeTrialResultStandings output = null;
    JSONParser parser = new JSONParser();
    try {/*from www  . j a  v  a 2s.c om*/
        JSONObject root = (JSONObject) parser.parse(json);
        Object o = root.get("d");
        if (o instanceof JSONObject) {
            JSONObject d = (JSONObject) o;
            output = new TimeTrialResultStandings();
            String s = (String) d.get("3");
            output.setApiUserRow(Integer.parseInt(s));
            output.setTotalRecords(getInt(d, "17"));
            JSONArray arrayRoot = (JSONArray) d.get("r");
            List<TimeTrialResultStanding> standings = new ArrayList<TimeTrialResultStanding>();
            for (int i = 0; i < arrayRoot.size(); i++) {
                JSONObject r = (JSONObject) arrayRoot.get(i);
                TimeTrialResultStanding standing = new TimeTrialResultStanding();
                o = r.get("1");
                if (o instanceof Double) {
                    standing.setPoints((Double) o);
                } else if (o instanceof Long) {
                    standing.setPoints(Double.parseDouble(String.valueOf(o)));
                }
                standing.setLicenseSubLevel(getString(r, "2"));
                standing.setMaxLicenseLevel(getInt(r, "4"));
                standing.setRank(getInt(r, "5"));
                standing.setDivision(getInt(r, "7"));
                standing.setDriverName(getString(r, "8", true));
                standing.setDriverCustomerId(getLong(r, "10"));
                standing.setTotalStarts(getInt(r, "12"));
                standing.setBestTimeFormatted(getString(r, "13", true));
                o = r.get("14");
                if (o instanceof Long) {
                    standing.setBestTime((Long) o);
                } else { // drivers setting no time will have an empty string ("14":"")
                    standing.setBestTime(-1L);
                }
                standing.setClubId(getInt(r, "15"));
                standing.setPosition(getLong(r, "18"));
                standings.add(standing);
            }
            output.setStandings(standings);
        }
    } catch (ParseException ex) {
        Logger.getLogger(TimeTrialResultStandingsParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:com.avatarproject.core.storage.UserCache.java

/**
 * Adds a player into the custom UserCache.
 * @param player Player to add to the cache.
 *//*www  .  ja v a  2s  .  c  om*/
@SuppressWarnings("unchecked")
public static void addUser(Player player) {
    String name = player.getName();
    UUID uuid = player.getUniqueId();
    JSONArray array = getUserCache();
    try {
        for (int n = 0; n < array.size(); n++) { //Loop through all the objects in the array.
            JSONObject object = (JSONObject) array.get(n);
            if (object.get("id").equals(uuid.toString())) { //Check if the player's UUID exists in the cache.
                if (String.valueOf(object.get("name")).equalsIgnoreCase(name)) {
                    return;
                } else {
                    object.put("name", name); //Update the user.
                    FileWriter fileOut = new FileWriter(usercache);
                    fileOut.write(array.toJSONString()); //Write the JSON array to the file.
                    fileOut.close();
                    return;
                }
            }
        }
        JSONObject newEntry = new JSONObject();
        newEntry.put("id", uuid.toString());
        newEntry.put("name", name);
        array.add(newEntry); //Add a new player into the cache.
        FileWriter fileOut = new FileWriter(usercache);
        fileOut.write(array.toJSONString()); //Write the JSON array to the file.
        fileOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.fabric8.jolokia.support.JolokiaHelpers.java

public static Object convertJolokiaToJavaType(Class<?> clazz, Object value) throws IOException {
    if (clazz.isArray()) {
        if (value instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) value;
            Object[] javaArray = (Object[]) Array.newInstance(clazz.getComponentType(), jsonArray.size());
            int idx = 0;
            for (Object element : jsonArray) {
                Array.set(javaArray, idx++, convertJolokiaToJavaType(clazz.getComponentType(), element));
            }/* w w w  .  j  a v a 2  s. c  o  m*/
            return javaArray;
        } else {
            return null;
        }
    } else if (String.class.equals(clazz)) {
        return (value != null) ? value.toString() : null;
    } else if (clazz.equals(Byte.class) || clazz.equals(byte.class)) {
        Number number = asNumber(value);
        return number != null ? number.byteValue() : null;
    } else if (clazz.equals(Short.class) || clazz.equals(short.class)) {
        Number number = asNumber(value);
        return number != null ? number.shortValue() : null;
    } else if (clazz.equals(Integer.class) || clazz.equals(int.class)) {
        Number number = asNumber(value);
        return number != null ? number.intValue() : null;
    } else if (clazz.equals(Long.class) || clazz.equals(long.class)) {
        Number number = asNumber(value);
        return number != null ? number.longValue() : null;
    } else if (clazz.equals(Float.class) || clazz.equals(float.class)) {
        Number number = asNumber(value);
        return number != null ? number.floatValue() : null;
    } else if (clazz.equals(Double.class) || clazz.equals(double.class)) {
        Number number = asNumber(value);
        return number != null ? number.doubleValue() : null;
    } else if (value instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) value;
        if (!JSONObject.class.isAssignableFrom(clazz)) {
            String json = jsonObject.toJSONString();
            return getObjectMapper().readerFor(clazz).readValue(json);
        }
    }
    return value;
}

From source file:naftoreiclag.villagefive.util.json.JSONUtil.java

public static <ConcreteJSONThingy extends JSONThingy> List<ConcreteJSONThingy> readList(JSONArray array,
        ConcreteJSONThingy expectedType) {
    List<ConcreteJSONThingy> newList = new ArrayList<ConcreteJSONThingy>();

    for (int i = 0; i < array.size(); ++i) {
        ConcreteJSONThingy thing = null;
        try {//w  w w . ja  v  a2s  .com
            //thing = (ConcreteJSONThingy) expectedType.getClass().getMethod("createFromJson", JSONObject.class).invoke(expectedType, array.get(i));
            thing = (ConcreteJSONThingy) expectedType.createFromJson((JSONObject) array.get(i));
            //thing = expectedType.getConstructor(JSONObject.class).newInstance(array.get(i));
        } catch (Exception ex) {
            Logger.getLogger(JSONThingy.class.getName()).log(Level.SEVERE, null, ex);
        }

        newList.add(thing);

    }

    return newList;
}

From source file:iracing.webapi.SessionResultSummaryParser.java

public static void parse(String json, ItemHandler handler) {
    if (handler != null) {
        JSONParser parser = new JSONParser();
        try {/*  w  w w.  ja v a 2  s .  co m*/
            JSONObject root = (JSONObject) parser.parse(json);
            //"1":"champpointssort","2":"raw_start_time","3":"bestlaptime","4":"start_time"
            //"5":"groupname","6":"helm_pattern","7":"season_year","8":"clubpoints","9":"subsession_bestlaptime"
            //"10":"evttype","11":"winnerlicenselevel","12":"strengthoffield","13":"dropracepoints","14":"finishedat"
            //"15":"trackid","16":"winnercustid","17":"custid","18":"winnerdisplayname","19":"sessionid"
            //"20":"clubpointssort","21":"rn","22":"seasonid","23":"carclassid","24":"helm_licenselevel"
            //"25":"starting_position","26":"officialsession","27":"displayname","28":"helm_color1","29":"season_quarter"
            //"30":"helm_color2","31":"helm_color3","32":"seriesid","33":"bestquallaptime","34":"licensegroup"
            //"35":"incidents","36":"champpoints","37":"race_week_num","38":"start_date","39":"winnerhelmcolor1"
            //"40":"winnerhelmcolor2","41":"winnerhelmcolor3","42":"carid","43":"subsessionid","44":"catid"
            //"45":"winnerhelmpattern","46":"rowcount","47":"finishing_position"

            // Only continue if 'd' is an JSONObject, not if it's an JSONArray (as is returned when invalid parameters are passed)
            // {"m":{},"d":[]}
            Object o = root.get("d");
            if (o instanceof JSONObject) {
                JSONObject d = (JSONObject) o;
                long totalRecords = getLong(d, "46");
                JSONArray r = (JSONArray) d.get("r");
                for (int i = 0; i < r.size(); i++) {
                    JSONObject rItem = (JSONObject) r.get(i);
                    SessionResultSummary summary = new SessionResultSummary();
                    //{"1":-1,"2":1339938000000,"3":"47.636","4":"01%3A00pm","5":"Rookie","6":48,"7":2012,"8":0,"9":"47.597",
                    //"10":5,"11":18,"12":1390,"13":"","14":1339940125000,"15":116,"16":72331,"17":29462,"18":"Robby+Singleton","19":25672697,
                    //"20":0,"21":1,"22":686,"23":19,"24":19,"25":6,"26":0,"27":"Christian+Aylward","28":111,"29":2,
                    //"30":255,"31":127,"32":116,"33":"","34":1,"35":4,"36":"","37":6,"38":"2012.06.17","39":22,
                    //"40":67,"41":39,"42":22,"43":5854525,"44":1,"45":56,"47":3}
                    summary.setStartTime(new Date(getLong(rItem, "2")));
                    summary.setBestLapTime(getString(rItem, "3"));
                    summary.setGroupName(getString(rItem, "5"));
                    summary.setSeasonYear(getInt(rItem, "7"));
                    String s = getString(rItem, "8");
                    if (!"".equals(s))
                        summary.setClubPoints(Integer.parseInt(s));
                    summary.setSessionBestLapTime(getString(rItem, "9"));
                    summary.setEventType(getInt(rItem, "10"));
                    summary.setWinnerLicenseLevel(getInt(rItem, "11"));
                    summary.setStrengthOfField(getInt(rItem, "12"));
                    s = getString(rItem, "13");
                    if (!"".equals(s))
                        summary.setDropRacePoints(Integer.parseInt(s));
                    summary.setFinishDate(new Date(getLong(rItem, "14")));
                    summary.setTrackId(getInt(rItem, "15"));
                    summary.setWinnerCustomerId(getLong(rItem, "16"));
                    summary.setCustomerId(getLong(rItem, "17"));
                    summary.setWinnerDisplayName(getString(rItem, "18", true));
                    summary.setSessionId(getLong(rItem, "19"));
                    summary.setSeasonId(getInt(rItem, "22"));
                    summary.setCarClassId(getInt(rItem, "23"));
                    summary.setStartingPosition(getInt(rItem, "25"));
                    summary.setOfficialSession((getInt(rItem, "26")) == 1);
                    summary.setDisplayName(getString(rItem, "27", true));
                    summary.setSeasonQuarter(getInt(rItem, "29"));
                    summary.setSeriesId(getInt(rItem, "32"));
                    summary.setBestQualifyingLapTime(getString(rItem, "33"));
                    summary.setLicenseGroup(getInt(rItem, "34"));
                    summary.setIncidents(getInt(rItem, "35"));
                    Object a = rItem.get("36");
                    if (a instanceof Long) {
                        summary.setChampionshipPoints(((Long) a).intValue());
                    }
                    //                        s = (String)rItem.get("36");
                    //                        if (!"".equals(s)) summary.setChampionshipPoints(Integer.parseInt(s));
                    summary.setRaceWeek(getInt(rItem, "37"));
                    summary.setStartDate(getString(rItem, "38"));
                    summary.setCarId(getInt(rItem, "42"));
                    summary.setSubSessionId(getLong(rItem, "43"));
                    summary.setCategoryId(getInt(rItem, "44"));
                    summary.setFinishingPosition(getInt(rItem, "47"));
                    if (!handler.onSessionResultSummaryParsed(summary))
                        break;
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(SessionResultSummaryParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:iracing.webapi.WorldRecordsParser.java

static WorldRecords parse(String json, boolean includeApiUserRow) {
    JSONParser parser = new JSONParser();
    WorldRecords output = null;/*from w w w . j a  v  a2s  .  com*/
    try {
        JSONObject root = (JSONObject) parser.parse(json);
        output = new WorldRecords();
        JSONObject root2 = (JSONObject) root.get("d");
        output.setApiUserRow(getLong(root2, "22"));
        output.setTotalResults(getLong(root2, "32"));
        JSONArray rootArray = (JSONArray) root2.get("r");
        List<WorldRecord> recordList = new ArrayList<WorldRecord>();
        for (int i = 0; i < rootArray.size(); i++) {
            JSONObject r = (JSONObject) rootArray.get(i);
            long recordNumber = getLong(r, "36");
            if (!includeApiUserRow && recordNumber == 0)
                continue;
            WorldRecord wr = new WorldRecord();
            wr.setClubName(getString(r, "1", true));
            wr.setCountryCode(getString(r, "2"));
            wr.setLicenseSubLevel(getInt(r, "3"));
            wr.setIrating(getInt(r, "4"));
            wr.setTimeTrialSubSessionId(getLong(r, "5"));
            wr.setQualify(getString(r, "6", true));
            IracingCustomer driver = new IracingCustomer();
            driver.setId(getLong(r, "26"));
            driver.setName(getString(r, "7", true));
            wr.setDriver(driver);
            long l = getLong(r, "8");
            if (l > 0)
                wr.setPracticeStartTime(new Date(l));
            wr.setSeasonQuarter(getInt(r, "9"));
            wr.setClubId(getInt(r, "10"));
            wr.setRace(getString(r, "11", true));
            wr.setLicenseSubLevelText(getString(r, "13", true));
            wr.setSeasonYear(getInt(r, "14"));
            wr.setTimeTrialRating(getInt(r, "15"));
            wr.setLicenseGroupId(getInt(r, "16"));
            wr.setRaceSubSessionId(getLong(r, "17"));
            l = getLong(r, "18");
            if (l > 0)
                wr.setTimeTrialStartTime(new Date(l));
            wr.setQualifyingSubSessionId(getLong(r, "19"));
            wr.setLicenseLevelId(getInt(r, "20"));
            wr.setTrackId(getInt(r, "21"));
            wr.setTimeTrial(getString(r, "23", true));
            wr.setCarId(getInt(r, "28"));
            wr.setCategoryId(getInt(r, "29"));
            wr.setRegionName(getString(r, "30", true));
            wr.setPracticeSubSessionId(getLong(r, "31"));
            l = getLong(r, "33");
            if (l > 0)
                wr.setRaceStartTime(new Date(l));
            wr.setPractice(getString(r, "34", true));
            l = getLong(r, "35");
            wr.setRecordNumber(recordNumber);
            if (l > 0)
                wr.setQualifyingStartTime(new Date(l));
            wr.setCategoryName(getString(r, "37"));
            recordList.add(wr);
        }
        output.setRecords(recordList);
    } catch (ParseException ex) {
        Logger.getLogger(WorldRecordsParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}