Example usage for org.json.simple.parser JSONParser JSONParser

List of usage examples for org.json.simple.parser JSONParser JSONParser

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser JSONParser.

Prototype

JSONParser

Source Link

Usage

From source file:jsonpractice.jsonpractice1.java

public static void main(String[] args) throws IOException, ParseException {
    JSONParser parser = new JSONParser();
    try {/*from  w w w .  ja  v  a 2  s  . c  om*/
        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:json.ReadFromFile.java

public static void main(String[] args) {

    JSONParser parser = new JSONParser();
    try {//  w  w  w  . j  a  va  2  s .c  o  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:dependencies.DependencyResolving.java

/**
 * @param args the command line arguments
 *//*from ww w.  ja  v  a  2 s. c  om*/
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:chat.jsonTest.java

/**
 * @param args the command line arguments
 *//*from ww w.j  a v a2s  .  com*/
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:MyTest.ParseJson.java

public static void main(String args[]) {
    try {/*from  w  w w . j  a  v  a  2  s  .  co m*/
        FileReader reader = new FileReader(
                new File("data/NGS___RNA-seq_differential_expression_analysis-v1.ga"));
        System.out.println(reader);
        JSONParser parser = new JSONParser();
        JSONObject jo = (JSONObject) parser.parse(reader);
        JSONObject jsteps = (JSONObject) jo.get("steps");

        System.out.println(jsteps.size());
        System.out.println("---------------------------------------------------");
        for (int i = 0; i < jsteps.size(); i++) {
            JSONObject jstep_detail = (JSONObject) jsteps.get(String.valueOf(i));
            getDetailInfo(jstep_detail);

        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(ParseJson.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ParseJson.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(ParseJson.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.devdungeon.simplejson.DecodeJson.java

public static void main(String[] args) {

    try {//  w  w w.  java  2  s  .  c o  m
        String jsonData = getJsonFromUrl("http://www.reddit.com/r/houston.json");

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonData); // The whole JSON value

        //System.out.println(jsonObject);
        JSONObject data = (JSONObject) jsonObject.get("data"); // The data object
        //System.out.println(data); 

        JSONArray children = (JSONArray) data.get("children"); // All children

        // for each child in children
        // get child("data")
        for (int i = 0; i < children.size(); i++) {
            JSONObject child = (JSONObject) children.get(i);
            //System.out.println(child); // The whole post object

            JSONObject childData = (JSONObject) child.get("data");
            System.out.print(childData.get("title") + ": ");
            System.out.println(childData.get("url"));
        }

    } catch (ParseException ex) {
        ex.printStackTrace();
    } catch (NullPointerException ex) {
        ex.printStackTrace();
    }

}

From source file:br.unicamp.ft.priva.aas.client.RESTUsageExample.java

public static void main(String[] args) {
    Object policyJSON, dataJSON;/*  www  .  ja v a2s  . c o  m*/
    //Example Data:
    String policyFile = "../priva-poc/input/example-mock-data/mock_data.policy.json";
    String dataFile = "../priva-poc/input/example-mock-data/mock_data.json";

    // Load Example Data:
    JSONParser parser = new JSONParser();
    try {

        FileReader policyReader = new FileReader(policyFile);
        policyJSON = parser.parse(policyReader);

        FileReader dataReader = new FileReader(dataFile);
        dataJSON = parser.parse(dataReader);
    } catch (IOException | ParseException e) {
        System.out.println("IOException | ParseException = " + e);
        return;
    }

    System.out.println("policyJSON = " + policyJSON.toString().length());
    System.out.println("dataJSON   = " + dataJSON.toString().length());

    JSONArray payload = new JSONArray();
    payload.add(policyJSON);
    payload.add(dataJSON);

    // POST data to server
    Client client = ClientBuilder.newClient();

    WebTarget statistics = client.target(ENDPOINT);
    String content = statistics.request(MediaType.APPLICATION_JSON)
            .post(Entity.entity(payload, MediaType.APPLICATION_JSON), String.class);

    System.out.println("result = " + content);

}

From source file:jnilibxml2.java

public static void main(String[] args) {
    // Create Json parser
    JSONParser parser = new JSONParser();
    // Create string that will hold the native call's return
    String[] LibReturnString = new String[args.length];
    Integer i = 0;//from   w  w w  .  j a  v  a 2 s.  c o  m
    if (args.length < 0) {
        System.out.println("Please supply a file to parse in commandline");
    }
    try {
        // allow the user to supply as many xml files as they wish
        for (i = 0; i < args.length; i++) {
            // run the native call on the file and get the string
            LibReturnString[i] = xmlparsefile(args[i]);
            Object obj = parser.parse(LibReturnString[i]);
            // JSON object is parsed and ready
            JSONObject jsonObject = (JSONObject) obj;
            // Dump it to output to confirm everything is functioning.
            System.out.println(jsonObject);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:my.yelp.populate.java

public static void main(String[] args)
        throws FileNotFoundException, ParseException, IOException, java.text.ParseException {
    try {/*from w ww. j ava  2  s .c  o m*/

        DbConnection A1 = new DbConnection();
        Connection con = A1.getConnection();

        JSONParser jsonParser;
        jsonParser = new JSONParser();

        Object obj1 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_user.json"));
        Object obj2 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_business.json"));
        Object obj3 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_review.json"));
        Object obj4 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_checkin.json"));

        JSONArray jsonArray1;
        jsonArray1 = (JSONArray) obj1;

        JSONArray jsonArray2;
        jsonArray2 = (JSONArray) obj2;

        JSONArray jsonArray3;
        jsonArray3 = (JSONArray) obj3;

        JSONArray jsonArray4;
        jsonArray4 = (JSONArray) obj4;

        // yelp_user
        String yelping_since, name1, user_id, type1;
        Long review_count1, fans;
        Double average_stars;
        Statement stmt;

        stmt = con.createStatement();
        stmt.executeUpdate("Delete from N_User");

        for (int i = 0; i < (jsonArray1.size()); i++)

        {
            JSONObject jsonObject = (JSONObject) jsonArray1.get(i);
            yelping_since = (String) jsonObject.get("yelping_since") + "-01";

            JSONArray friends = (JSONArray) jsonObject.get("friends");
            int friends_size = friends.size();

            review_count1 = (Long) jsonObject.get("review_count");
            name1 = (String) jsonObject.get("name");
            user_id = (String) jsonObject.get("user_id");
            fans = (Long) jsonObject.get("fans");
            average_stars = (Double) jsonObject.get("average_stars");
            type1 = (String) jsonObject.get("type");

            try (PreparedStatement pstmt1 = con.prepareStatement(
                    "Insert INTO N_User(yelping_since,friends_size,review_count,name,user_id,fans,average_stars,type) VALUES(?,?,?,?,?,?,?,?)")) {

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date myDate = format.parse(yelping_since);

                pstmt1.setDate(1, new java.sql.Date(myDate.getTime()));
                pstmt1.setInt(2, friends_size);
                pstmt1.setLong(3, review_count1);
                pstmt1.setString(4, name1);
                pstmt1.setString(5, user_id);
                pstmt1.setLong(6, fans);
                pstmt1.setDouble(7, average_stars);
                pstmt1.setString(8, type1);
                pstmt1.executeUpdate();
            } catch (java.text.ParseException ex) {
                Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        //yelp_business

        String business_id, address, city, state, name, type_business;

        Double stars;

        for (int i = 0; i < jsonArray2.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray2.get(i);
            business_id = (String) jsonObject.get("business_id");
            address = (String) jsonObject.get("full_address");
            city = (String) jsonObject.get("city");
            state = (String) jsonObject.get("state");
            name = (String) jsonObject.get("name");
            stars = (Double) jsonObject.get("stars");
            type_business = (String) jsonObject.get("type");

            try (PreparedStatement pstmt2 = con.prepareStatement(
                    "Insert INTO N_Business(business_id,address,city,state,name,stars,type_business) VALUES(?,?,?,?,?,?,?)")) {
                pstmt2.setString(1, business_id);
                pstmt2.setString(2, address);
                pstmt2.setString(3, city);
                pstmt2.setString(4, state);
                pstmt2.setString(5, name);
                pstmt2.setDouble(6, stars);
                pstmt2.setString(7, type_business);
                pstmt2.executeUpdate();
                pstmt2.close();
            }

        }

        //Category Table
        String[] categories = { "Active Life", "Arts & Entertainment", "Automotive", "Car Rental", "Cafes",
                "Beauty & Spas", "Convenience Stores", "Dentists", "Doctors", "Drugstores", "Department Stores",
                "Education", "Event Planning & Services", "Flowers & Gifts", "Food", "Health & Medical",
                "Home Services", "Home & Garden", "Hospitals", "Hotels & travel", "Hardware stores", "Grocery",
                "Medical Centers", "Nurseries & Gardening", "Nightlife", "Restaurants", "Shopping",
                "Transportation" };

        JSONArray category;
        String[] individual_category = new String[100];
        int count = 0, flag = 0, m = 0, n = 0;
        String[] business_category = new String[50];
        String[] subcategory = new String[50];

        for (int i = 0; i < jsonArray2.size(); i++) {
            JSONObject jsonObject3 = (JSONObject) jsonArray2.get(i);
            String business_id2 = (String) jsonObject3.get("business_id");
            category = (JSONArray) jsonObject3.get("categories");
            for (int j = 0; j < category.size(); j++) {
                individual_category[j] = (String) category.get(j);
                count = count + 1;
            }
            for (int k = 0; k < count; k++) {
                for (String categorie : categories) {

                    if (individual_category[k].equals(categorie)) {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 1) {
                    business_category[m] = individual_category[k];
                    m = m + 1;
                    flag = 0;
                } else {
                    subcategory[n] = individual_category[k];
                    n = n + 1;
                }
            }
            for (int p = 0; p < m; p++) {
                for (int q = 0; q < n; q++) {
                    try (PreparedStatement pstmt3 = con.prepareStatement(
                            "INSERT INTO N_Category(business_id,category,subcategory) VALUES(?,?,?)")) {
                        pstmt3.setString(1, business_id2);
                        pstmt3.setString(2, business_category[p]);
                        pstmt3.setString(3, subcategory[q]);
                        pstmt3.executeUpdate();

                    }
                }
            }
            count = 0;
            m = 0;
            n = 0;
        }

        //yelp_review

        String user_id3, review_id, type3, business_id3, text, text1, review_date;
        Long stars3;
        int votes = 0;
        Integer no_votes;

        JSONObject votes_info;
        Set<String> keys;

        for (int i = 0; i < jsonArray3.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray3.get(i);

            votes_info = (JSONObject) jsonObject.get("votes");
            keys = votes_info.keySet();
            for (String r_key : keys) {
                votes = (int) (votes + (Long) votes_info.get(r_key));
            }
            no_votes = toIntExact(votes);
            user_id3 = (String) jsonObject.get("user_id");

            review_id = (String) jsonObject.get("review_id");
            business_id3 = (String) jsonObject.get("business_id");
            review_date = (String) jsonObject.get("date");
            text1 = (String) jsonObject.get("text");
            text = text1.substring(0, Math.min(1000, text1.length()));
            stars3 = (Long) jsonObject.get("stars");
            type3 = (String) jsonObject.get("type");

            try (PreparedStatement pstmt4 = con.prepareStatement(
                    "Insert INTO N_Review(no_votes,user_id,review_id,business_id,review_date,text,stars,type) VALUES(?,?,?,?,?,?,?,?)")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date myDate = format.parse(review_date);

                pstmt4.setInt(1, no_votes);
                pstmt4.setString(2, user_id3);
                pstmt4.setString(3, review_id);
                pstmt4.setString(4, business_id3);
                pstmt4.setDate(5, new java.sql.Date(myDate.getTime()));
                pstmt4.setString(6, text);
                pstmt4.setLong(7, stars3);
                pstmt4.setString(8, type3);
                pstmt4.executeUpdate();
                pstmt4.close();
            }

        }

        //Checkin_Info
        JSONObject checkin_info;
        String business_id4;
        Long check_in_count;
        Set<String> keys1;
        String[] timing = new String[10];
        int n1 = 0, time, hour;

        //Inserting into checkin_info
        for (int i = 0; i < jsonArray4.size(); i++) {
            JSONObject jsonObject4 = (JSONObject) jsonArray4.get(i);
            checkin_info = (JSONObject) jsonObject4.get("checkin_info");
            business_id4 = (String) jsonObject4.get("business_id");
            keys1 = checkin_info.keySet();

            for (String key : keys1) {
                check_in_count = (Long) checkin_info.get(key);
                for (String x : key.split("-")) {
                    timing[n1] = x;
                    n1 = n1 + 1;
                }
                n1 = 0;
                hour = Integer.parseInt(timing[0]);
                time = Integer.parseInt(timing[1]);

                try (PreparedStatement pstmt5 = con.prepareStatement(
                        "INSERT INTO check_info(business_id,hour,day,check_in_count)VALUES(?,?,?,?)")) {
                    pstmt5.setString(1, business_id4);
                    pstmt5.setInt(2, hour);
                    pstmt5.setInt(3, time);
                    pstmt5.setLong(4, check_in_count);
                    pstmt5.executeUpdate();
                }
            }

        }

        con.close();

    } catch (SQLException ex) {
        Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.aj.hangman.HangmanReq.java

public static void main(String[] args) {
    HangmanDict dictionary = new HangmanDict();

    try {//from  w w w  . j  a  v a2  s.  co m
        BufferedReader input = new BufferedReader(new InputStreamReader(
                new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu").openStream()));
        String info = input.readLine();
        JSONParser parser = new JSONParser();

        Object obj;
        try {
            obj = parser.parse(info);
            JSONObject retJson = (JSONObject) obj;

            TOKEN = (String) retJson.get("token");
            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            PREM = REM;
            System.out.println("State:: " + STATE);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while ("ALIVE".equalsIgnoreCase(STATUS)) {
            // call make guess function, returns character
            guess = dictionary.makeGuess(STATE);
            System.out.println("Guessed:: " + guess);
            // call the url to update
            BufferedReader reInput = new BufferedReader(
                    new InputStreamReader(new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu"
                            + String.format("&token=%s&guess=%s", TOKEN, guess)).openStream()));

            // parse the url to get the updated value
            String reInfo = reInput.readLine();
            JSONParser reParser = new JSONParser();

            Object retObj = reParser.parse(reInfo);
            JSONObject retJson = (JSONObject) retObj;

            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            System.out.println("State:: " + STATE);
        }

        if ("DEAD".equalsIgnoreCase(STATUS)) {
            // print lost
            System.out.println("You LOOSE: DEAD");
        } else if ("FREE".equalsIgnoreCase(STATUS)) {
            // print free
            System.out.println("You WIN: FREE");
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}