Example usage for org.json.simple JSONObject getOrDefault

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

Introduction

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

Prototype

default V getOrDefault(Object key, V defaultValue) 

Source Link

Document

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

Usage

From source file:jomr5bphotos.Model.java

private void parseJSON(String json) throws Exception {
    JSONObject jsonObj = null;

    try {//from   w  w  w. j av a 2s .co  m
        jsonObj = (JSONObject) JSONValue.parse(json);
    } catch (Exception e) {
        System.out.println("Failed to parse JSON document.");
        throw e;
    }

    //json parsed successfully...
    String status = jsonObj.getOrDefault("status", null).toString();

    if (status == null || status.equals("ok") == false) {
        System.out.println("Status was not 'OK'");
        throw new Exception();
    }

    //status OK, so start loading objects
    JSONArray pictures = null;

    try {
        pictures = (JSONArray) jsonObj.get("photos");
    } catch (Exception e) {
        throw new Exception("Failed to load photos array.");
    }

    //load photo path
    try {
        _photoPath = (String) jsonObj.get("photosPath");
    } catch (Exception e) {
        throw new Exception("Failed to load the photo path.");
    }

    System.out.println("Test: ");
    System.out.format("Status: %s\nPath: %s\n", status, _photoPath);

    //go through each picture and parse a new object
    for (Object picture : pictures) {
        String date, description, filename, latitude, longitude, title;
        jsonObj = (JSONObject) picture;
        filename = (String) jsonObj.get("image");
        title = (String) jsonObj.get("title");
        description = (String) jsonObj.get("description");
        latitude = ((Double) jsonObj.get("latitude")).toString();
        longitude = ((Double) jsonObj.get("longitude")).toString();
        date = (String) jsonObj.get("date");

        System.out.println("==================");
        System.out.format("Title:  %s\n" + "File Name: %s\n" + "Description: %s\n" + "Date: %s\n"
                + "Latitude: %s\n" + "Longitude: %s\n", title, filename, description, date, latitude,
                longitude);

        PictureDataHolder holder = new PictureDataHolder(date, description, filename, latitude, longitude,
                title);
        this._pictureData.add(holder);
    }
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

private void setDataPoint(final DataPoint DATA_POINT, final JSONObject JSON_OBJ) {
    DATA_POINT.setTime(epochStringToLocalDateTime(JSON_OBJ.getOrDefault("time", 0).toString()));
    DATA_POINT.setSummary(JSON_OBJ.getOrDefault("summary", "").toString());
    DATA_POINT.setCondition(Condition
            .valueOf(JSON_OBJ.getOrDefault("icon", "none").toString().toUpperCase().replace("-", "_")));
    DATA_POINT.setSunriseTime(epochStringToLocalDateTime(JSON_OBJ.getOrDefault("sunriseTime", 0).toString()));
    DATA_POINT.setSunsetTime(epochStringToLocalDateTime(JSON_OBJ.getOrDefault("sunsetTime", 0).toString()));
    DATA_POINT.setMoonPhase(Double.parseDouble(JSON_OBJ.getOrDefault("moonPhase", 0).toString()));
    DATA_POINT.setPrecipIntensity(Double.parseDouble(JSON_OBJ.getOrDefault("precipIntensity", 0).toString()));
    DATA_POINT.setPrecipIntensityMax(/*  ww w.j  a v a2  s. c o  m*/
            Double.parseDouble(JSON_OBJ.getOrDefault("precipIntensityMax", 0).toString()));
    DATA_POINT.setPrecipIntensityMaxTime(
            epochStringToLocalDateTime(JSON_OBJ.getOrDefault("precipIntensityMaxTime", 0).toString()));
    DATA_POINT
            .setPrecipProbability(Double.parseDouble(JSON_OBJ.getOrDefault("precipProbability", 0).toString()));
    DATA_POINT.setPrecipType(PrecipType
            .valueOf(JSON_OBJ.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_")));
    DATA_POINT.setTemperature(Double.parseDouble(JSON_OBJ.getOrDefault("temperature", 0).toString()));
    DATA_POINT.setTemperatureMin(Double.parseDouble(JSON_OBJ.getOrDefault("temperatureMin", 0).toString()));
    DATA_POINT.setTemperatureMinTime(
            epochStringToLocalDateTime(JSON_OBJ.getOrDefault("temperatureMinTime", 0).toString()));
    DATA_POINT.setTemperatureMax(Double.parseDouble(JSON_OBJ.getOrDefault("temperatureMax", 0).toString()));
    DATA_POINT.setTemperatureMaxTime(
            epochStringToLocalDateTime(JSON_OBJ.getOrDefault("temperatureMaxTime", 0).toString()));
    DATA_POINT.setApparentTemperatureMin(
            Double.parseDouble(JSON_OBJ.getOrDefault("apparentTemperatureMin", 0).toString()));
    DATA_POINT.setApparentTemperatureMinTime(
            epochStringToLocalDateTime(JSON_OBJ.getOrDefault("apparentTemperatureMinTime", 0).toString()));
    DATA_POINT.setApparentTemperatureMax(
            Double.parseDouble(JSON_OBJ.getOrDefault("apparentTemperatureMax", 0).toString()));
    DATA_POINT.setApparentTemperatureMaxTime(
            epochStringToLocalDateTime(JSON_OBJ.getOrDefault("apparentTemperatureMaxTime", 0).toString()));
    DATA_POINT.setDewPoint(Double.parseDouble(JSON_OBJ.getOrDefault("dewPoint", 0).toString()));
    DATA_POINT.setHumidity(Double.parseDouble(JSON_OBJ.getOrDefault("humidity", 0).toString()));
    DATA_POINT.setWindSpeed(Double.parseDouble(JSON_OBJ.getOrDefault("windSpeed", 0).toString()));
    DATA_POINT.setWindBearing(Double.parseDouble(JSON_OBJ.getOrDefault("windBearing", 0).toString()));
    DATA_POINT.setCloudCover(Double.parseDouble(JSON_OBJ.getOrDefault("cloudCover", 0).toString()));
    DATA_POINT.setPressure(Double.parseDouble(JSON_OBJ.getOrDefault("pressure", 0).toString()));
    DATA_POINT.setOzone(Double.parseDouble(JSON_OBJ.getOrDefault("ozone", 0).toString()));
    DATA_POINT.setNearestStormBearing(
            Double.parseDouble(JSON_OBJ.getOrDefault("nearestStormBearing", 0).toString()));
    DATA_POINT.setNearestStormDistance(
            Double.parseDouble(JSON_OBJ.getOrDefault("nearestStormDistance", 0).toString()));
    DATA_POINT
            .setPrecipAccumlation(Double.parseDouble(JSON_OBJ.getOrDefault("precipAccumlation", 0).toString()));
    DATA_POINT.setVisibility(Double.parseDouble(JSON_OBJ.getOrDefault("visibility", 0).toString()));
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

public boolean update(final double LATITUDE, final double LONGITUDE) {
    // Update only if lastUpdate is older than 10 min
    if (Instant.now().minusSeconds(600).isBefore(lastUpdate))
        return true;

    StringBuilder response = new StringBuilder();
    try {//from  w  w w . j av  a  2s .c  o m
        forecast.clear();
        alerts.clear();

        final String URL_STRING = createUrl(LATITUDE, LONGITUDE, unit, language, Exclude.HOURLY,
                Exclude.MINUTELY, Exclude.FLAGS);
        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;

        latitude = Double.parseDouble(jsonObj.getOrDefault("latitude", 0).toString());
        longitude = Double.parseDouble(jsonObj.getOrDefault("longitude", 0).toString());
        timeZone = TimeZone.getTimeZone(jsonObj.getOrDefault("timezone", "").toString());

        // Update today data
        JSONObject currently = (JSONObject) jsonObj.get("currently");
        setDataPoint(today, currently);

        // Update forecast data
        JSONObject daily = (JSONObject) jsonObj.get("daily");
        JSONArray days = (JSONArray) daily.get("data");

        // Update today with more data
        JSONObject day0 = (JSONObject) days.get(0);
        today.setSunriseTime(epochStringToLocalDateTime(day0.getOrDefault("sunriseTime", 0).toString()));
        today.setSunsetTime(epochStringToLocalDateTime(day0.getOrDefault("sunsetTime", 0).toString()));
        today.setPrecipProbability(Double.parseDouble(day0.getOrDefault("precipProbability", 0).toString()));
        today.setPrecipType(PrecipType
                .valueOf(day0.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_")));

        for (int i = 1; i < days.size(); i++) {
            JSONObject day = (JSONObject) days.get(i);
            DataPoint dataPoint = new DataPoint();
            setDataPoint(dataPoint, day);
            forecast.add(dataPoint);
        }

        // Update alert data
        if (jsonObj.containsKey("alerts")) {
            JSONArray alerts = (JSONArray) jsonObj.get("alerts");
            for (Object alertObj : alerts) {
                JSONObject alertJson = (JSONObject) alertObj;
                Alert alert = new Alert();
                alert.setTitle(alertJson.get("title").toString());
                alert.setDescription(alertJson.get("description").toString());
                alert.setTime(epochStringToLocalDateTime(alertJson.getOrDefault("time", 0).toString()));
                alert.setExpires(epochStringToLocalDateTime(alertJson.getOrDefault("expires", 0).toString()));
                alerts.add(alert);
            }
        }

        lastUpdate = Instant.now();

        return true;
    } catch (IOException ex) {
        System.out.println(ex);
        return false;
    }
}

From source file:nytimesviewer.NYTNewsStory.java

private static void parseJsonNewsFeed(String jsonString) throws Exception {
    // start with clean list
    getNewsStories().clear();//from  ww  w  .j  a  v a  2  s  .  c o m

    if (jsonString == null || jsonString.isEmpty())
        return;

    JSONObject jsonObj;
    try {
        System.out.println("About to parse JSON string");
        jsonObj = (JSONObject) JSONValue.parse(jsonString);
    } catch (Exception ex) {
        throw ex;
    }

    if (jsonObj == null)
        return;

    String status = "";
    try {
        status = (String) jsonObj.get("status");
    } catch (Exception ex) {
        throw ex;
    }

    if (status == null || !status.equals("OK")) {
        throw new Exception("Status returned from API was not OK.");
    }

    JSONObject response;
    try {
        response = (JSONObject) jsonObj.get("response");
    } catch (Exception ex) {
        throw ex;
    }

    JSONArray docs;
    try {
        docs = (JSONArray) response.get("docs");
    } catch (Exception ex) {
        throw ex;
    }

    for (Object doc : docs) {
        try {
            JSONObject story = (JSONObject) doc;
            String webUrl = (String) story.getOrDefault("web_url", "");
            String snippet = (String) story.getOrDefault("snippet", "");
            String leadParagraph = (String) story.getOrDefault("lead_paragraph", "");
            String source = (String) story.getOrDefault("source", "");
            String newsDesk = (String) story.getOrDefault("news_desk", "");
            String sectionName = (String) story.getOrDefault("section_name", "");
            JSONObject headlineObj = (JSONObject) story.getOrDefault("headline", null);
            String headline = "";
            if (headlineObj != null) {
                headline = (String) headlineObj.getOrDefault("main", "");
            }

            System.out.println("headline: " + headline + "\n");
            System.out.println("webUrl: " + webUrl + "\n");
            System.out.println("snippet: " + snippet + "\n");
            System.out.println("leadParagraph: " + leadParagraph + "\n");
            System.out.println("newsDesk: " + newsDesk + "\n");
            System.out.println("sectionName: " + sectionName + "\n");
            System.out.println("source: " + source + "\n");
            System.out.println("------------------------------------------------------\n");

            NYTNewsStory newsStory = new NYTNewsStory(webUrl, headline, snippet, leadParagraph, newsDesk,
                    sectionName, source);
            getNewsStories().add(newsStory);
        } catch (Exception ex) {
            throw ex;
        }

    }

}

From source file:org.bunkr.core.inventory.FileInventoryItemJSON.java

@SuppressWarnings("unchecked")
public static FileInventoryItem decodeO(JSONObject input) {
    byte[] encD = null;
    if (input.getOrDefault(KEY_ENCRYPTION_DATA, null) != null)
        encD = DatatypeConverter.parseBase64Binary((String) input.get(KEY_ENCRYPTION_DATA));

    byte[] intH = null;
    if (input.getOrDefault(KEY_INTEGRITY_HASH, null) != null)
        intH = DatatypeConverter.parseBase64Binary((String) input.get(KEY_INTEGRITY_HASH));

    Algorithms.Encryption encA = Algorithms.Encryption.NONE;
    if (input.getOrDefault(KEY_ENCRYPTION_ALGORITHM, null) != null)
        encA = Algorithms.Encryption.valueOf((String) input.get(KEY_ENCRYPTION_ALGORITHM));

    String mt = MediaType.UNKNOWN;
    if (input.getOrDefault(KEY_MEDIA_TYPE, null) != null) {
        mt = (String) input.get(KEY_MEDIA_TYPE);
        if (!MediaType.ALL_TYPES.contains(mt)) {
            Logging.warn("File %s has unsupported media type %s. Converting to %s", input.get(KEY_NAME), mt,
                    MediaType.UNKNOWN);
            mt = MediaType.UNKNOWN;
        }/*from   w w  w  .ja v  a2s .  c o m*/
    }

    return new FileInventoryItem((String) input.get(KEY_NAME), UUID.fromString((String) input.get(KEY_UUID)),
            FragmentedRangeJSON.decode((JSONArray) input.get(KEY_BLOCKS)), (Long) input.get(KEY_SIZE_ON_DISK),
            (Long) input.get(KEY_ACTUAL_SIZE), (Long) input.get(KEY_MODIFIED_AT), encD, encA, intH, mt);
}

From source file:org.wwscc.storage.Run.java

@Override
public void decode(String str) throws ParseException {
    try {/*ww  w.  j a  v a  2  s .  c  o m*/
        JSONObject in = (JSONObject) (new JSONParser().parse(str));
        course = (int) (long) in.getOrDefault("course", -1);
        run = (int) (long) in.getOrDefault("run", -1);
        raw = (double) in.getOrDefault("raw", -1);
        status = (String) in.getOrDefault("status", "OK");
        attr = (JSONObject) in.getOrDefault("attr", new JSONObject());
    } catch (Exception e) {
        log.log(Level.INFO, String.format("Can't decode run from %s: %s", str, e), e);
    }
}