Example usage for org.json.simple JSONArray iterator

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

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:chat.jsonTest.java

/**
 * @param args the command line arguments
 */// w  w w.  ja va 2s. c o  m
public static void main(String[] args) throws ParseException, IOException {
    // TODO code application logic here
    JSONParser parser = new JSONParser();
    String fullPath = "userInfo.json";
    //BufferedReader reader = new BufferedReader(new FileReader(fullPath));

    Object obj = parser.parse(new FileReader("userInfo.json"));
    JSONObject jsonObject = (JSONObject) obj;
    /*while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }*/
    JSONArray lang = (JSONArray) jsonObject.get("userInfo");
    Iterator i = lang.iterator();

    // take each value from the json array separately
    while (i.hasNext()) {
        JSONObject innerObj = (JSONObject) i.next();
        System.out
                .println("username " + innerObj.get("username") + " with password " + innerObj.get("password"));
    }

}

From source file:json.ReadFromFile.java

public static void main(String[] args) {

    JSONParser parser = new JSONParser();
    try {//from   w ww. j  a  v  a2s .co m
        Object obj = parser.parse(new FileReader(file));
        JSONObject jsonObject = (JSONObject) obj;
        String countryName = jsonObject.get("Name") + "";//equivalent to jsonObject.get("Name").toString(); 
        System.out.println("Name of Country: " + countryName);

        long population = (long) jsonObject.get("Population");
        System.out.println("Population: " + population);

        System.out.println("Counties are:");
        JSONArray listOfCounties = (JSONArray) jsonObject.get("Counties");
        Iterator<String> iterator = listOfCounties.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

From source file:jsonpractice.jsonpractice1.java

public static void main(String[] args) throws IOException, ParseException {
    JSONParser parser = new JSONParser();
    try {//from  w  ww. j  a v a2 s.c o m
        Object obj = parser.parse(new FileReader("C:\\Users\\user\\Documents\\CountryJSONFile.json"));
        JSONObject jsonobject = (JSONObject) obj;

        String nameOfCountry = (String) jsonobject.get("Name");
        System.out.println("Name of the Country: " + nameOfCountry);

        long population = (long) jsonobject.get("Population");
        System.out.println("Population of the country is : " + population);

        System.out.println("States are: ");
        JSONArray listOfStates = (JSONArray) jsonobject.get("states");

        Iterator<String> iterator = listOfStates.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    } catch (ParseException e) {
    }

}

From source file:dependencies.DependencyResolving.java

/**
 * @param args the command line arguments
 */// w w  w  .ja va  2 s .c o m
public static void main(String[] args) {
    // TODO code application logic here
    JSONParser parser = new JSONParser(); //we use JSONParser in order to be able to read from JSON file
    try { //here we declare the file reader and define the path to the file dependencies.json
        Object obj = parser.parse(new FileReader(
                "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\dependencies.json"));
        JSONObject project = (JSONObject) obj; //a JSON object containing all the data in the .json file
        JSONArray dependencies = (JSONArray) project.get("dependencies"); //get array of objects with key "dependencies"
        System.out.print("We need to install the following dependencies: ");
        Iterator<String> iterator = dependencies.iterator(); //define an iterator over the array "dependencies"
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        } //on the next line we declare another object, which parses a Parser object and reads from all_packages.json
        Object obj2 = parser.parse(new FileReader(
                "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\all_packages.json"));
        JSONObject tools = (JSONObject) obj2; //a JSON object containing all thr data in the file all_packages.json
        for (int i = 0; i < dependencies.size(); i++) {
            if (tools.containsKey(dependencies.get(i))) {
                System.out.println(
                        "In order to install " + dependencies.get(i) + ", we need the following programs:");
                JSONArray temporaryArray = (JSONArray) tools.get(dependencies.get(i)); //a temporary JSON array in which we store the keys and values of the dependencies
                for (i = 0; i < temporaryArray.size(); i++) {
                    System.out.println(temporaryArray.get(i));
                }
                ArrayList<Object> arraysOfJsonData = new ArrayList<Object>(); //an array in which we will store the keys of the objects, after we use the values and won't need them anymore
                for (i = 0; i < temporaryArray.size(); i++) {
                    System.out.println("Installing " + temporaryArray.get(i));
                }
                while (!temporaryArray.isEmpty()) {

                    for (Object element : temporaryArray) {

                        if (tools.containsKey(element)) {
                            JSONArray secondaryArray = (JSONArray) tools.get(element); //a temporary array within the scope of the if-statement
                            if (secondaryArray.size() != 0) {
                                System.out.println("In order to install " + element + ", we need ");
                            }
                            for (i = 0; i < secondaryArray.size(); i++) {
                                System.out.println(secondaryArray.get(i));
                            }

                            for (Object o : secondaryArray) {

                                arraysOfJsonData.add(o);
                                //here we create a file with the installed dependency
                                File file = new File(
                                        "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\"
                                                + o);
                                if (file.createNewFile()) {
                                    System.out.println(file.getName() + " is installed!");
                                } else {
                                }
                            }
                            secondaryArray.clear();
                        }
                    }
                    temporaryArray.clear();
                    for (i = 0; i < arraysOfJsonData.size(); i++) {
                        temporaryArray.add(arraysOfJsonData.get(i));
                    }
                    arraysOfJsonData.clear();
                }
            }
        }
        Set<String> keys = tools.keySet(); // here we define a set of keys of the objects in all_packages.json
        for (String s : keys) {
            File file = new File(
                    "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\"
                            + s);
            if (file.createNewFile()) {
                System.out.println(file.getName() + " is installed.");
            } else {
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:authorship.verification.ReadJSON.java

public static String readJson(String file) {
    JSONParser parser = new JSONParser();
    try {//from   ww  w  .ja v  a 2s  .  co  m
        FileReader fileReader = new FileReader(file);
        JSONObject json = (JSONObject) parser.parse(fileReader);

        language = (String) json.get("language");
        //System.out.println("Language: " + language); 

        JSONArray filenames = (JSONArray) json.get("problems");
        Iterator i = filenames.iterator();
        /*System.out.println("Filenames: "); 
        while (i.hasNext()) { 
        System.out.println(" " + i.next()); 
        } */
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return language;
}

From source file:com.punyal.blackhole.utils.Parsers.java

public static JSONObject senml2json(String s) {
    JSONObject json, tmp;/* w  ww  .ja  v a 2  s  .c  om*/
    String data;

    json = new JSONObject();
    try {
        tmp = (JSONObject) JSONValue.parse(s);

        // Save base time
        json.put("time", tmp.get("bt"));

        JSONArray slideContent = (JSONArray) tmp.get("e");
        Iterator i = slideContent.iterator();

        while (i.hasNext()) {
            JSONObject slide = (JSONObject) i.next();
            json.put(slide.get("n"), slide.get("v"));
        }
    } catch (NullPointerException e) {
    }
    return json;
}

From source file:currencyexchange.JSONCurrency.java

public static ArrayList<CurrencyUnit> getCurrencyUnitsJSON() {
    try {//  w ww . j  a v  a2s .c  o  m
        FileReader reader = new FileReader(filePath);

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

        JSONArray currencyUnits = (JSONArray) jsonObject.get("units");

        ArrayList<CurrencyUnit> currencies = new ArrayList<CurrencyUnit>();

        Iterator i = currencyUnits.iterator();
        while (i.hasNext()) {
            JSONObject e = (JSONObject) i.next();
            CurrencyUnit currency = new CurrencyUnit((String) e.get("CountryCurrency"),
                    (String) e.get("Units"));

            currencies.add(currency);
        }
        return currencies;

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (ParseException | NullPointerException ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:edu.rit.chrisbitler.ritcraft.slackintegration.rtm.UserList.java

/**
 * Query the slack api to get the list of users and their real names. This is done whenever we can't find an ID mapping,
 * and when the plugin loads//from  w  w  w  . j  av a  2s  .c  o  m
 */
public static void queryUsers() {
    try {
        users.clear();
        //Contact the slack api to get the user list
        HttpURLConnection conn = (HttpURLConnection) new URL(
                "https://www.slack.com/api/users.list?token=" + SlackIntegration.BOT_TOKEN).openConnection();
        conn.connect();
        JSONObject retVal = (JSONObject) JSONValue
                .parse(new InputStreamReader((InputStream) conn.getContent()));
        JSONArray members = (JSONArray) retVal.get("members");

        //Loop through the members and add them to the map
        Iterator<JSONObject> iter = members.iterator();
        while (iter.hasNext()) {
            JSONObject obj = iter.next();
            JSONObject profile = (JSONObject) obj.get("profile");
            String id = (String) obj.get("id");
            String realName = (String) profile.get("real_name");
            users.put(id, realName);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.marklogic.tableauextract.ExtractFromJSON.java

/**
 * Read JSON output from MarkLogic REST extension or *.xqy file and insert
 * the output into a Tabeleau table// w w w .  j  av  a2  s .  com
 * 
 * @param table
 * @throws TableauException
 */
private static void insertData(Table table)
        throws TableauException, FileNotFoundException, ParseException, IOException {
    TableDefinition tableDef = table.getTableDefinition();
    Row row = new Row(tableDef);

    URL url = new URL("http://localhost:8060/json.xqy");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(bufferedReader);

    JSONArray claims = (JSONArray) jsonObject.get("claims");

    @SuppressWarnings("unchecked")
    Iterator<JSONObject> i = claims.iterator();

    while (i.hasNext()) {
        JSONObject innerObject = i.next();

        String idString = (String) innerObject.get("id");
        row.setInteger(0, Integer.parseInt(idString.substring(0, 6)));
        row.setCharString(1, (String) innerObject.get("ssn"));
        row.setCharString(2, (String) innerObject.get("type"));
        String payString = (String) innerObject.get("payment_amount");
        if (payString == null || payString.isEmpty())
            payString = "0.0";
        row.setDouble(3, Double.parseDouble(payString));
        String dtString = (String) innerObject.get("claim_date");
        if (dtString == null || dtString.isEmpty())
            dtString = "1999-01-01";
        LocalDate claimDate = (LocalDate.parse(dtString));
        row.setDate(4, claimDate.getYear(), claimDate.getMonthValue(), claimDate.getDayOfMonth());
        table.insert(row);

    }

    /*
    row.setDateTime(  0, 2012, 7, 3, 11, 40, 12, 4550); // Purchased
    row.setCharString(1, "Beans");                      // Product
    row.setString(    2, "uniBeans");                   // uProduct
    row.setDouble(    3, 1.08);                         // Price
    row.setDate(      6, 2029, 1, 1);                   // Expiration date
    row.setCharString(7, "Bohnen");                     // Produkt
            
    for ( int i = 0; i < 10; ++i ) {
    row.setInteger(4, i * 10);                      // Quantity
    row.setBoolean(5, i % 2 == 1);                  // Taxed
    }
    */
}

From source file:com.baystep.jukeberry.JsonConfiguration.java

public static SourceDescription[] getSourceDescriptionArray(JSONObject obj, String key) {
    ArrayList<SourceDescription> list = new ArrayList<>();
    JSONArray array = (JSONArray) obj.get(key);
    if (array != null) {
        Iterator it = array.iterator();
        while (it.hasNext()) {
            JSONObject element = (JSONObject) it.next();

            SourceDescription sd = new SourceDescription();
            sd.name = element.get("name").toString();
            sd.fqn = element.get("fqn").toString();

            list.add(sd);//from  w w  w .ja  va2  s.  c  om
        }
    }
    SourceDescription[] output = new SourceDescription[list.size()];
    list.toArray(output);
    return output;
}