Example usage for org.json.simple JSONObject get

List of usage examples for org.json.simple JSONObject get

Introduction

In this page you can find the example usage for org.json.simple JSONObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.tom.deleteme.PrintAnnotations.java

public static void appendOtherNamedTags(JSONObject json, String coveredText) {
    String otherNamedTags = (String) json.get(OtherNamedTagsKey);
    StringJoiner joiner = new StringJoiner(",");
    joiner.add(otherNamedTags).add(coveredText);
    String joinedString = joiner.toString();
    json.put(OtherNamedTagsKey, joinedString);
}

From source file:edu.emory.library.viaf.ViafClient.java

/**
 * Query the VIAF AutoSuggest API to get suggestions matches for
 * a user-specified search term.  Returns an empty list if
 * no matches were found or if there was an error either making
 * the request or parsing the response.//from   ww  w .ja v a 2  s. c  om
 *
 * @param term  search term
 * @return      list of ViafResource
 */
public static List<ViafResource> suggest(String term) throws Exception {

    String uri = String.format("%s/AutoSuggest?query=%s", baseUrl, URLEncoder.encode(term, "UTF-8"));
    String result = EULHttpUtils.readUrlContents(uri);
    // todo: handle (at least log) http exceptions here

    List<ViafResource> resources = new ArrayList<ViafResource>();

    try {
        // parse the JSON and initialize a list of ViafResource objects
        // viaf autosuggest returns  in json format, with a list of results
        JSONObject json = (JSONObject) new JSONParser().parse(result);
        JSONArray jsonArray = (JSONArray) json.get("result");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = (JSONObject) jsonArray.get(i);

            // initialize a ViafResource for each result, using the viaf id and term
            // results may also include the following identifiers:
            //   lc, dnb, bnf, bne, nkc, nlilat, nla
            ViafResource vr = new ViafResource((String) obj.get("viafid"), (String) obj.get("term"));
            resources.add(vr);
        }

    } catch (Exception e) {
        // json parsing error - should just result in any empty resource list
        // TODO: log the error ?
    }
    return resources;
}

From source file:eu.hansolo.fx.weatherfx.GeoCode.java

/**
 * Returns name of City for given latitude and longitude
 * @param LATITUDE//w  w w. ja  v  a  2 s .com
 * @param LONGITUDE
 * @return name of City for given latitude and longitude
 */
public static String inverseGeoCode(final double LATITUDE, final double LONGITUDE) {
    String URL_STRING = new StringBuilder(INVERSE_GEO_CODE_URL).append(LATITUDE).append(",").append(LONGITUDE)
            .append("&outFormat=json&thumbMaps=false").toString();

    StringBuilder response = new StringBuilder();
    try {
        final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection();
        final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream()));
        String inputLine;
        while ((inputLine = IN.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        IN.close();

        Object obj = JSONValue.parse(response.toString());
        JSONObject jsonObj = (JSONObject) obj;

        JSONArray results = (JSONArray) jsonObj.get("results");
        JSONObject firstResult = (JSONObject) results.get(0);
        JSONArray locations = (JSONArray) firstResult.get("locations");
        JSONObject firstLocation = (JSONObject) locations.get(0);
        return firstLocation.get("adminArea5").toString();
    } catch (IOException ex) {
        System.out.println(ex);
        return "";
    }
}

From source file:autoancillarieslimited.parser.ParserUtil.java

public static WareHouses parserWarehouses(String dataJson) {
    try {/*from  ww  w .  ja  v a2s .c  o m*/
        WareHouses i = new WareHouses();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(dataJson);
        JSONObject jsonObject = (JSONObject) obj;
        int id = Integer.parseInt((String) jsonObject.get("P0"));
        String name = (String) jsonObject.get("P1");
        String address = (String) jsonObject.get("P2");
        String phone = (String) jsonObject.get("P3");
        String email = (String) jsonObject.get("P4");
        int region_ID = Integer.parseInt((String) jsonObject.get("P5"));
        i.setId(id);
        i.setName(name);
        i.setAddress(address);
        i.setPhone(phone);
        i.setEmail(email);
        i.setRegion_ID(region_ID);
        return i;
    } catch (Exception ex) {
        return null;
    }
}

From source file:eu.hansolo.fx.weatherfx.GeoCode.java

/**
 * Returns a JavaFX Point2D object that contains latitude (y) and longitude(x) of the given
 * Address./*from ww  w  .  j a  v  a  2 s  . c om*/
 * Example format for STREET_CITY_COUNTRY: "1060 W. Addison St., Chicago IL, 60613"
 * @param STREET_CITY_COUNTRY
 * @return a JavaFX Point2D object that contains latitude(y) and longitude(x) of given address
 */
public static Point2D geoCode(final String STREET_CITY_COUNTRY) throws UnsupportedEncodingException {
    String URL_STRING = new StringBuilder(GEO_CODE_URL).append(URLEncoder.encode(STREET_CITY_COUNTRY, "UTF-8"))
            .append("&thumbMaps=false").toString();

    StringBuilder response = new StringBuilder();
    try {
        final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection();
        final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream()));
        String inputLine;
        while ((inputLine = IN.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        IN.close();

        Object obj = JSONValue.parse(response.toString());
        JSONObject jsonObj = (JSONObject) obj;

        JSONArray results = (JSONArray) jsonObj.get("results");
        JSONObject firstResult = (JSONObject) results.get(0);
        JSONArray locations = (JSONArray) firstResult.get("locations");
        JSONObject firstLocation = (JSONObject) locations.get(0);
        JSONObject latLng = (JSONObject) firstLocation.get("latLng");
        return new Point2D(Double.parseDouble(latLng.get("lng").toString()),
                Double.parseDouble(latLng.get("lat").toString()));
    } catch (IOException ex) {
        System.out.println(ex);
        return new Point2D(0, 0);
    }
}

From source file:freebase.api.FreebaseHelper.java

public static JSONArray getJSON(String fromDate, String toDate) {
    try {/*from w w  w  . j a v a2s  .c o m*/
        properties.load(new FileInputStream("freebase.properties"));
        HttpTransport httpTransport = new NetHttpTransport();
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
        JSONParser parser = new JSONParser();
        String query = readQueryFromFile("queries/q1.json");
        query = manipulateQuery(query, fromDate, toDate);
        GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
        url.put("query", query);
        url.put("key", properties.get("API_KEY"));
        System.out.println("URL:" + url);
        HttpRequest request = requestFactory.buildGetRequest(url);
        HttpResponse httpResponse = request.execute();
        JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
        JSONArray results = (JSONArray) response.get("result");
        Utils.writeDataIntoFile(results.toString() + "\n", FreebaseAPI.JSON_DUMP_FILE);

        return results;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:br.com.RatosDePC.Brpp.compiler.BrppCompiler.java

public static boolean compile(String path) {
    setFile(FileUtils.getBrinodirectory() + System.getProperty("file.separator") + "Arduino");
    setFile(getFile()// ww w  .  j ava2 s  .  c om
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 5)));
    setFile(getFile()
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 4)));
    setFile(getFile().concat("ino"));
    File ino = new File(getFile());
    if (!ino.exists()) {
        try {
            ino.getParentFile().mkdirs();
            ino.createNewFile();
        } catch (IOException e) {

        }
    }
    try {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        String code = new String(encoded);
        JSONArray Keywords = JSONUtils.getKeywords();
        @SuppressWarnings("unchecked")
        Iterator<JSONObject> iterator = Keywords.iterator();
        while (iterator.hasNext()) {
            JSONObject key = iterator.next();
            String arg = (String) key.get("arg");
            if (arg.equals("false")) {
                code = code.replace((String) key.get("translate"), (String) key.get("arduino"));
            } else {
                code = code.replaceAll((String) key.get("translate"), (String) key.get("arduino"));
            }
        }

        try (FileWriter file = new FileWriter(getFile())) {
            file.write(code);
        }
        System.out.println(code);
        return true;

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

}

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  a2s.  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.speedment.examples.social.JSONImage.java

public static List<JSONImage> parseFrom(String json) {

    final JSONObject container = (JSONObject) JSONValue.parse(json);
    final JSONArray array = (JSONArray) container.get("images");
    final List<JSONImage> images = new ArrayList<>();

    array.stream().forEach(o -> {/*from   www .  ja v  a2  s .c o m*/
        final JSONObject obj = (JSONObject) o;
        final JSONImage img = new JSONImage();
        final long time = Long.parseLong(obj.get("uploaded").toString());

        final LocalDateTime ldt = LocalDateTime.ofEpochSecond(time / 1000L, (int) (time % 1000) * 1000,
                ZoneOffset.UTC);

        img.title = obj.get("title").toString();
        img.description = obj.get("description").toString();
        img.uploaded = ldt;
        img.uploader = JSONUser.parse((JSONObject) obj.get("uploader"));
        img.image = fromBase64(obj.get("img_data").toString());
        images.add(img);
    });

    Collections.sort(images, Comparator.reverseOrder());

    return images;
}

From source file:iracing.webapi.DriverStatsParser.java

static DriverStats parse(String json, boolean includeApiUserTopRow) {
    JSONParser parser = new JSONParser();
    DriverStats output = null;// w ww. j a  v  a2s  .  com
    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;
}