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

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

Introduction

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

Prototype

public Object parse(Reader in) throws IOException, ParseException 

Source Link

Usage

From source file:json.ReadFromFile.java

public static void main(String[] args) {

    JSONParser parser = new JSONParser();
    try {/*from w  ww . j  a v a2 s .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   www .j av  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:com.devdungeon.simplejson.DecodeJson.java

public static void main(String[] args) {

    try {/*from  w ww  . j ava  2s .  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:MyTest.ParseJson.java

public static void main(String args[]) {
    try {/*from w  w  w. j a  v a  2s  .  c  o 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:br.unicamp.ft.priva.aas.client.RESTUsageExample.java

public static void main(String[] args) {
    Object policyJSON, dataJSON;//from w  w  w .ja v  a  2  s .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:chat.jsonTest.java

/**
 * @param args the command line arguments
 *///from  w  ww  .  j  a v  a2 s.c om
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:com.aj.hangman.HangmanReq.java

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

    try {//www. j  a  va2 s  .com
        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();
    }

}

From source file:com.github.artifactresolver.MavenDependencyDownloader.java

public static void main(String[] args) throws Exception {

    new MavenDependencyDownloader();

    parseCommandLine(args);//from w  ww.  j a v  a 2s .c  om

    RepositorySystemHelper repoSystemHelper = new RepositorySystemHelper(localRepo);
    dependencyResolver = new DependencyResolver(repoSystemHelper);

    if (artifacts.isEmpty()) {
        JSONParser jsonParser = new JSONParser();
        FileReader fileReader = new FileReader(new File(dependencyFile));
        JSONArray jsonArray = (JSONArray) jsonParser.parse(fileReader);
        fileReader.close();

        for (Object obj : jsonArray) {
            JSONObject jsonObj = (JSONObject) obj;
            String groupId = (String) jsonObj.get("groupId");
            String artifactId = (String) jsonObj.get("artifactId");
            String classifier = (String) jsonObj.get("classifier");
            String extension = (String) jsonObj.get("extension");
            String version = (String) jsonObj.get("version");

            DefaultArtifact artifact = new DefaultArtifact(groupId, artifactId, classifier, extension, version);
            dependencyResolver.downloadDependencyTree(artifact, javadoc, sources);
        }
    } else {
        for (DefaultArtifact artifact : artifacts) {
            dependencyResolver.downloadDependencyTree(artifact, javadoc, sources);
        }
    }
    log.info("Artifacts downloaded to \"{}\". Finished. Thank you.", localRepo);
}

From source file:dependencies.DependencyResolving.java

/**
 * @param args the command line arguments
 *///w w  w .ja  v a 2s  . 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:OCRRestAPI.java

public static void main(String[] args) throws Exception {
    /*//from   ww w . j  ava 2  s. c  o  m
              
         Sample project for OCRWebService.com (REST API).
         Extract text from scanned images and convert into editable formats.
         Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code
            
     */

    // Provide your user name and license code
    String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D";
    String user_name = "FERGOID";

    /*
            
      You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide
             
      Input parameters:
             
     [language]      - Specifies the recognition language. 
                  This parameter can contain several language names separated with commas. 
                    For example "language=english,german,spanish".
               Optional parameter. By default:english
            
     [pagerange]     - Enter page numbers and/or page ranges separated by commas. 
               For example "pagerange=1,3,5-12" or "pagerange=allpages".
                    Optional parameter. By default:allpages
             
      [tobw]           - Convert image to black and white (recommend for color image and photo). 
               For example "tobw=false"
                    Optional parameter. By default:false
             
      [zone]          - Specifies the region on the image for zonal OCR. 
               The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. 
               This parameter can contain several zones separated with commas. 
                 For example "zone=0:0:100:100,50:50:50:50"
                    Optional parameter.
              
      [outputformat]  - Specifies the output file format.
                    Can be specified up to two output formats, separated with commas.
               For example "outputformat=pdf,txt"
                    Optional parameter. By default:doc
            
      [gettext]      - Specifies that extracted text will be returned.
               For example "tobw=true"
                    Optional parameter. By default:false
            
       [description]  - Specifies your task description. Will be returned in response.
                    Optional parameter. 
            
            
     !!!!  For getting result you must specify "gettext" or "outputformat" !!!!  
            
    */

    // Build your OCR:

    // Extraction text with English language
    String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";

    // Extraction text with English and German language using zonal OCR
    ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400";

    // Convert first 5 pages of multipage document into doc and txt
    // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt";

    // Full path to uploaded document
    String filePath = "sarah-morgan.jpg";

    byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

    URL url = new URL(ocrURL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Authorization",
            "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes()));

    // Specify Response format to JSON or XML (application/json or application/xml)
    connection.setRequestProperty("Content-Type", "application/json");

    connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

    int httpCode;
    try (OutputStream stream = connection.getOutputStream()) {

        // Send POST request
        stream.write(fileContent);
        stream.close();
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    httpCode = connection.getResponseCode();

    System.out.println("HTTP Response code: " + httpCode);

    // Success request
    if (httpCode == HttpURLConnection.HTTP_OK) {
        // Get response stream
        String jsonResponse = GetResponseToString(connection.getInputStream());

        // Parse and print response from OCR server
        PrintOCRResponse(jsonResponse);
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        System.out.println("OCR Error Message: Unauthorizied request");
    } else {
        // Error occurred
        String jsonResponse = GetResponseToString(connection.getErrorStream());

        JSONParser parser = new JSONParser();
        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);

        // Error message
        System.out.println("Error Message: " + jsonObj.get("ErrorMessage"));
    }

    connection.disconnect();

}