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:com.mtag.traffic.util.JsonTools.java

public static JSONObject requestService(String service) throws JsonServiceException {
    InputStream is = null;/*from www.  java2s .c  om*/
    try {
        URL url = new URL(service);
        JSONParser parser = new JSONParser();
        is = url.openStream();
        JSONObject result = (JSONObject) parser.parse(new BufferedReader(new InputStreamReader(is)));
        is.close();
        return result;
    } catch (MalformedURLException ex) {
        throw new JsonServiceException("Bad service address", ex);
    } catch (IOException ex) {
        throw new JsonServiceException("Service '" + service + "' not available.", ex);
    } catch (ParseException ex) {
        throw new JsonServiceException("Error parsind service '" + service + "'.", ex);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                throw new JsonServiceException("unable to close input stream", ex);
            }
        }
    }
}

From source file:com.serena.rlc.provider.jenkins.domain.JobParameter.java

public static List<JobParameter> parse(String options) {
    List<JobParameter> list = new ArrayList<>();
    JSONParser parser = new JSONParser();
    try {/*w w  w .j  a  va 2 s .c  o  m*/
        Object parsedObject = parser.parse(options);
        JSONArray array = (JSONArray) ((JSONObject) parsedObject).get("actions");
        for (Object action : array) {
            JSONArray paramDefs = (JSONArray) ((JSONObject) action).get("parameterDefinitions");

            if (paramDefs != null && paramDefs.size() > 0) {
                for (Object param : paramDefs) {
                    JobParameter obj = new JobParameter();
                    JSONObject jsonObject = (JSONObject) param;

                    obj.setName((String) jsonObject.get("name"));
                    obj.setType((String) jsonObject.get("type"));

                    try {
                        JSONObject deafultValueJsonObject = (JSONObject) jsonObject
                                .get("defaultParameterValue");
                        obj.setDefaultValue((String) deafultValueJsonObject.get("value"));
                    } catch (Exception ex) {
                    }

                    list.add(obj);
                }
            }
        }
    } catch (ParseException e) {
        logger.error("Error while parsing input JSON - " + options, e);
    }

    return list;
}

From source file:fr.itldev.koya.webscript.KoyaWebscript.java

/**
 * Extracts JSON POST data./*from   w  w  w .  jav a2 s. c  om*/
 *
 * @param req
 * @return
 * @throws java.io.IOException
 */
public static Map<String, Object> getJsonMap(WebScriptRequest req) throws IOException {

    JSONParser parser = new JSONParser();
    // TODO improve json POST reading
    try {
        return (JSONObject) parser.parse(req.getContent().getContent());
    } catch (ParseException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }

    return new HashMap<>();

}

From source file:iracing.webapi.DriverStatsParser.java

static DriverStats parse(String json, boolean includeApiUserTopRow) {
    JSONParser parser = new JSONParser();
    DriverStats output = null;/*from   w  w w  .  j  a  v a2  s.co m*/
    try {
        JSONObject root = (JSONObject) parser.parse(json);
        JSONObject root2 = (JSONObject) root.get("d");
        output = new DriverStats();
        output.setApiUserRow(getLong(root2, "24"));
        output.setTotalRecords(getLong(root2, "33"));
        JSONArray arrayRoot = (JSONArray) root2.get("r");
        List<DriverStat> statList = new ArrayList<DriverStat>();
        for (int i = 0; i < arrayRoot.size(); i++) {
            JSONObject r = (JSONObject) arrayRoot.get(i);
            long recordNumber = getLong(r, "37");
            if (!includeApiUserTopRow && recordNumber == 0)
                continue;
            DriverStat ds = new DriverStat();
            ds.setClubName(getString(r, "1", true));
            ds.setCountryCode(getString(r, "2", true));
            ds.setLicenseSubLevel(getInt(r, "3"));
            ds.setIratingRank(getLong(r, "4"));
            ds.setAverageFinishingPosition(getInt(r, "5"));
            ds.setIrating(getInt(r, "6"));
            ds.setLicenseGroupName(getString(r, "7", true));
            IracingCustomer driver = new IracingCustomer();
            driver.setName(getString(r, "8", true));
            driver.setId(getLong(r, "29"));
            ds.setDriver(driver);
            ds.setTimeTrialRatingRank(getLong(r, "9"));
            ds.setAverageIncidentsPerRace(getDouble(r, "10"));
            ds.setTotalTop25PercentFinishes(getLong(r, "11"));
            ds.setClubId(getInt(r, "12"));
            ds.setTotalStarts(getLong(r, "13"));
            ds.setLicenseClassRank(getLong(r, "15"));
            ds.setTotalLapsLed(getLong(r, "16"));
            ds.setTotalWins(getLong(r, "17"));
            ds.setTotalClubPoints(getLong(r, "18"));
            ds.setTimeTrialRating(getInt(r, "19"));
            ds.setLicenseGroupId(getInt(r, "20"));
            ds.setLicenseLevelId(getInt(r, "21"));
            ds.setTotalChampionshipPoints(getLong(r, "22"));
            ds.setLicenseGroupLetter(getString(r, "23", true));
            ds.setAverageFieldSize(getInt(r, "25"));
            ds.setRank(getLong(r, "26"));
            ds.setRegionName(getString(r, "31", true));
            ds.setAveragePointsPerRace(getInt(r, "32"));
            ds.setTotalLaps(getLong(r, "34"));
            ds.setLicenseClass(getString(r, "35", true));
            ds.setAverageStartingPosition(getInt(r, "36"));
            ds.setRecordNumber(recordNumber);
            statList.add(ds);
        }
        output.setStats(statList);
    } catch (ParseException ex) {
        Logger.getLogger(DriverStatsParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:com.serena.rlc.provider.artifactory.domain.Artifact.java

public static Artifact parseSingle(String options) {
    JSONParser parser = new JSONParser();
    try {//from  w  w  w.  ja v a2 s .  co m
        Object parsedObject = parser.parse(options);
        Artifact artifact = parseSingle((JSONObject) parsedObject);
        return artifact;
    } catch (ParseException e) {
        logger.error("Error while parsing input JSON - " + options, e);
    }
    return null;
}

From source file:de.rub.nds.burp.utilities.Encoding.java

/**
 * Check if the the input is JSON.//w  w  w  .ja v  a2s. c o m
 * @param data The input to check.
 * @return True if data is JSON, false otherwise. 
 */
public static boolean isJSON(String data) {
    JSONParser parser = new JSONParser();
    try {
        JSONObject json = (JSONObject) parser.parse(data);
    } catch (ParseException e) {
        return false;
    }
    return true;
}

From source file:com.wso2.rfid.apicalls.APICall.java

/**
 * Populates Token object using folloing JSON String
 * {/*  w  w  w .j a  va2  s . c o  m*/
 * "token_type": "bearer",
 * "expires_in": 3600000,
 * "refresh_token": "f43de118a489d56c3b3b7ba77a1549e",
 * "access_token": "269becaec9b8b292906b3f9e69b5a9"
 * }
 *
 * @param accessTokenJson
 * @return
 */
public static Token getAccessToken(String accessTokenJson) {
    JSONParser parser = new JSONParser();
    Token token = null;
    try {
        Object obj = parser.parse(accessTokenJson);
        JSONObject jsonObject = (JSONObject) obj;
        token = new Token();
        token.setAccessToken((String) jsonObject.get("access_token"));
        long expiresIn = ((Long) jsonObject.get("expires_in")).intValue();
        token.setExpiresIn(expiresIn);
        token.setRefreshToken((String) jsonObject.get("refresh_token"));
        token.setTokenType((String) jsonObject.get("token_type"));
    } catch (ParseException e) {
        log.error("", e);
    }
    return token;
}

From source file:io.github.casnix.spawnerdropper.SpawnerStack.java

public static long GetSpawnersInService(String spawnerType) {
    try {//from   www .  j a v a 2s  .c  om
        // Read entire ./SpawnerDropper.SpawnerStack.json into a string
        String spawnerStack = new String(
                Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json")));

        // get the value of JSON->{spawnerType}
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(spawnerStack);

        JSONObject jsonObj = (JSONObject) obj;

        long number = (Long) jsonObj.get(spawnerType);

        //         System.out.println("[SD DBG MSG] GSIS numberInServer("+number+")");

        return number;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in GetSpawnersInService(String)");
        e.printStackTrace();

        return -1;
    } catch (FileNotFoundException e) {
        Bukkit.getLogger()
                .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json");
        e.printStackTrace();

        return -1;
    } catch (IOException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in GetSpawnersInService(String)");
        e.printStackTrace();

        return -1;
    }

}

From source file:OCRRestAPI.java

private static void PrintOCRResponse(String jsonResponse) throws ParseException, IOException {
    // Parse JSON data
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);

    // Get available pages
    System.out.println("Available pages: " + jsonObj.get("AvailablePages"));

    // get an array from the JSON object
    JSONArray text = (JSONArray) jsonObj.get("OCRText");

    // For zonal OCR: OCRText[z][p]    z - zone, p - pages
    for (int i = 0; i < text.size(); i++) {
        System.out.println(" " + text.get(i));
    }/*from  www  . ja  va  2  s.  c  o  m*/

    // Output file URL
    String outputFileUrl = (String) jsonObj.get("OutputFileUrl");

    // If output file URL is specified
    if (outputFileUrl != null && !outputFileUrl.equals("")) {
        // Download output file
        DownloadConvertedFile(outputFileUrl);
    }
}

From source file:Bing.java

/**
 *
 * @param query - query to use for the search
 * @return - a json array of results. each contains a title, description, url,
 * and some other metadata that can be easily extracted since its in json format
 *///from w w w .  j  av  a2  s  . c om
public static JSONArray search(String query) {
    try {
        query = "'" + query + "'";
        String encodedQuery = URLEncoder.encode(query, "UTF-8");
        System.out.println(encodedQuery);
        //            URL url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27car%27");
        //            URL url = new URL("http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html");
        String webPage = "https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query="
                + encodedQuery + "&$format=JSON";
        String name = "6604d12c-3e89-4859-8013-3132f78c1595";
        String password = "cefgNRl3OL4PrJJvssxkqLw0VKfYNCgyTe8wNXotUmQ";

        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }

        in.close();
        JSONParser parser = new JSONParser();
        JSONArray arr = (JSONArray) ((JSONObject) ((JSONObject) parser.parse(response.toString())).get("d"))
                .get("results");
        JSONObject obj = (JSONObject) arr.get(0);
        JSONArray out = (JSONArray) obj.get("Web");

        return out;

        //

    } catch (MalformedURLException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}