Example usage for org.json JSONObject isNull

List of usage examples for org.json JSONObject isNull

Introduction

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

Prototype

public boolean isNull(String key) 

Source Link

Document

Determine if the value associated with the key is null or if there is no value.

Usage

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java

public void close(String omeXML) throws IOException {
    writeNullOffsetAfterLastImage();//from w w  w. j a va 2  s  .c  o  m
    writeIndexMap();

    String summaryComment = "";
    try {
        JSONObject comments = masterMPTiffStorage_.getDisplayAndComments().getJSONObject("Comments");
        ;
        if (comments.has("Summary") && !comments.isNull("Summary")) {
            summaryComment = comments.getString("Summary");
        }
    } catch (Exception e) {
        ReportingUtils.logError("Could't get acquisition summary comment from displayAndComments");
    }
    writeImageJMetadata(numChannels_, summaryComment);

    if (omeTiff_) {
        try {
            writeImageDescription(omeXML, omeDescriptionTagPosition_);
        } catch (Exception ex) {
            ReportingUtils.showError("Error writing OME metadata");
        }
    }
    writeImageDescription(getIJDescriptionString(), ijDescriptionTagPosition_);

    writeDisplaySettings();
    writeComments();

    //extra byte of space, just to make sure nothing gets cut off
    raFile_.setLength(filePosition_ + 8);
    reader_.finishedWriting();
    //Dont close file channel and random access file becase Tiff reader still using them
    fileChannel_ = null;
    raFile_ = null;
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java

private void processSummaryMD(JSONObject summaryMD) throws MMScriptException, JSONException {
    rgb_ = MDUtils.isRGB(summaryMD);/*from  w  ww  . ja  v a  2 s  . c om*/
    numChannels_ = MDUtils.getNumChannels(summaryMD);
    numFrames_ = MDUtils.getNumFrames(summaryMD);
    numSlices_ = MDUtils.getNumSlices(summaryMD);
    imageWidth_ = MDUtils.getWidth(summaryMD);
    imageHeight_ = MDUtils.getHeight(summaryMD);
    String pixelType = MDUtils.getPixelType(summaryMD);
    if (pixelType.equals("GRAY8") || pixelType.equals("RGB32") || pixelType.equals("RGB24")) {
        byteDepth_ = 1;
    } else if (pixelType.equals("GRAY16") || pixelType.equals("RGB64")) {
        byteDepth_ = 2;
    } else if (pixelType.equals("GRAY32")) {
        byteDepth_ = 3;
    } else {
        byteDepth_ = 2;
    }
    bytesPerImagePixels_ = imageHeight_ * imageWidth_ * byteDepth_ * (rgb_ ? 3 : 1);
    //Tiff resolution tag values
    double cmPerPixel = 0.0001;
    if (summaryMD.has("PixelSizeUm")) {
        try {
            cmPerPixel = 0.0001 * summaryMD.getDouble("PixelSizeUm");
        } catch (JSONException ex) {
        }
    } else if (summaryMD.has("PixelSize_um")) {
        try {
            cmPerPixel = 0.0001 * summaryMD.getDouble("PixelSize_um");
        } catch (JSONException ex) {
        }
    }
    double log = Math.log10(cmPerPixel);
    if (log >= 0) {
        resDenomenator_ = (long) cmPerPixel;
        resNumerator_ = 1;
    } else {
        resNumerator_ = (long) (1 / cmPerPixel);
        resDenomenator_ = 1;
    }

    if (summaryMD.has("z-step_um") && !summaryMD.isNull("z-step_um")) {
        zStepUm_ = summaryMD.getDouble("z-step_um");
    }
}

From source file:org.mixare.data.convert.TwitterDataProcessor.java

@Override
public List<Marker> load(String rawData, int taskId, int colour) throws JSONException {
    List<Marker> markers = new ArrayList<Marker>();
    JSONObject root = convertToJSON(rawData);
    JSONArray dataArray = root.getJSONArray("results");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    for (int i = 0; i < top; i++) {
        JSONObject jo = dataArray.getJSONObject(i);

        Marker ma = null;//from  www  .  j a v a 2  s  . c  om
        if (jo.has("geo")) {
            Double lat = null, lon = null;

            if (!jo.isNull("geo")) {
                JSONObject geo = jo.getJSONObject("geo");
                JSONArray coordinates = geo.getJSONArray("coordinates");
                lat = Double.parseDouble(coordinates.getString(0));
                lon = Double.parseDouble(coordinates.getString(1));
            } else if (jo.has("location")) {

                // Regex pattern to match location information
                // from the location setting, like:
                // iPhone: 12.34,56.78
                // T: 12.34,56.78
                // 12.34,56.78

                Pattern pattern = Pattern.compile("\\D*([0-9.]+),\\s?([0-9.]+)");
                Matcher matcher = pattern.matcher(jo.getString("location"));

                if (matcher.find()) {
                    lat = Double.parseDouble(matcher.group(1));
                    lon = Double.parseDouble(matcher.group(2));
                }
            }
            if (lat != null) {
                Log.v(MixView.TAG, "processing Twitter JSON object");
                String user = jo.getString("from_user");
                String url = "http://twitter.com/" + user;

                //no ID is needed, since identical tweet by identical user may be safely merged into one.
                ma = new SocialMarker("", user + ": " + jo.getString("text"), lat, lon, 0, url, taskId, colour);
                markers.add(ma);
            }
        }
    }
    return markers;
}

From source file:com.appjma.appdeployer.service.JSONHelper.java

public static JSONArray getJSONArrayOrDefault(JSONObject json, String key, JSONArray defaultValue)
        throws JSONException {
    if (json.isNull(key)) {
        return defaultValue;
    }/*from   w w  w . j a v  a 2s  .  com*/
    return json.getJSONArray(key);
}

From source file:com.appjma.appdeployer.service.JSONHelper.java

private static void throwIfKeyIsNull(JSONObject json, String key) throws JSONException {
    if (json.isNull(key)) {
        throw new JSONException("Key \"" + key + "\" is null");
    }/*  w w w  .j  av  a2 s  .co  m*/
}

From source file:com.appjma.appdeployer.service.JSONHelper.java

public static String getStringOrDefault(JSONObject json, String key, String defaultValue) throws JSONException {
    if (json.isNull(key)) {
        return defaultValue;
    }//from   www  .  j a v a  2 s.  c  o  m
    return json.getString(key);
}

From source file:edu.pdx.its.portal.routelandia.entities.TrafficStat.java

public TrafficStat(JSONObject jsonObject) throws JSONException {
    //get hour, minute, speed, and travel time from each json obj
    this.hour = Integer.parseInt(jsonObject.getString("hour"));
    this.minutes = Integer.parseInt(jsonObject.getString("minute"));
    this.speed = 0.0;

    if (!jsonObject.isNull("speed")) {
        this.speed = Double.parseDouble(jsonObject.getString("speed"));
    }//w w  w.j a  v a 2s .c om
    this.travelTime = 0.0;
    if (!jsonObject.isNull("traveltime")) {
        this.travelTime = Double.parseDouble(jsonObject.getString("traveltime"));
    }
    this.accuracy = 0.0;
    if (!jsonObject.isNull("accuracy")) {
        this.accuracy = Double.parseDouble(jsonObject.getString("accuracy"));
    }
    this.distance = 0.0;
    if (!jsonObject.isNull("distance")) {
        this.distance = Double.parseDouble(jsonObject.getString("distance"));
    }
}

From source file:com.polychrom.cordova.ActionBarPlugin.java

private boolean buildMenu(Menu menu, JSONArray definition, String menu_var) {
    // Sadly MenuItem.setIcon and SubMenu.setIcon have conficting return types (for chaining), thus this can't be done w/ generics :(
    class GetMenuItemIconTask extends AsyncTask<String, Void, Drawable> {
        public final MenuItem item;
        public Exception exception = null;

        GetMenuItemIconTask(MenuItem item) {
            this.item = item;
        }// w w  w. ja  v a 2s.co  m

        @Override
        protected Drawable doInBackground(String... uris) {
            return getDrawableForURI(uris[0]);
        }

        @Override
        protected void onPostExecute(Drawable icon) {
            if (icon != null) {
                item.setIcon(icon);
            }
        }
    }
    ;

    class GetSubMenuIconTask extends AsyncTask<String, Void, Drawable> {
        public final SubMenu item;
        public Exception exception = null;

        GetSubMenuIconTask(SubMenu item) {
            this.item = item;
        }

        @Override
        protected Drawable doInBackground(String... uris) {
            return getDrawableForURI(uris[0]);
        }

        @Override
        protected void onPostExecute(Drawable icon) {
            if (icon != null) {
                item.setIcon(icon);
            }
        }
    }
    ;

    try {
        for (int i = 0; i < definition.length(); ++i) {
            final JSONObject item_def = definition.getJSONObject(i);
            final String text = item_def.isNull("text") ? "" : item_def.getString("text");

            if (!item_def.has("items")) {
                MenuItem item = menu.add(0, i, i, text);
                item.setTitleCondensed(text);
                if (item_def.isNull("icon") == false) {
                    GetMenuItemIconTask task = new GetMenuItemIconTask(item);

                    synchronized (task) {
                        task.execute(item_def.getString("icon"));
                    }
                }

                // Default to MenuItem.SHOW_AS_ACTION_IF_ROOM, otherwise take user defined value.
                item.setShowAsAction(item_def.has("show") ? item_def.getInt("show")
                        : MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

                menu_callbacks.put(item,
                        "var item = " + menu_var + "[" + i + "]; if(item.click) item.click();");
            } else {
                SubMenu submenu = menu.addSubMenu(0, i, i, text);
                if (item_def.isNull("icon") == false) {
                    GetSubMenuIconTask task = new GetSubMenuIconTask(submenu);

                    synchronized (task) {
                        task.execute(item_def.getString("icon"));
                    }
                }

                // Set submenu header
                if (item_def.has("header")) {
                    JSONObject header = item_def.getJSONObject("header");

                    if (header.has("title")) {
                        submenu.setHeaderTitle(header.getString("title"));
                    }

                    if (header.has("icon")) {
                        submenu.setHeaderIcon(getDrawableForURI(header.getString("icon")));
                    }
                }

                // Build sub-menu
                buildMenu(submenu, item_def.getJSONArray("items"), menu_var + "[" + i + "].items");
            }
        }
    } catch (JSONException e) {
        return false;
    }

    return true;
}

From source file:com.polychrom.cordova.ActionBarPlugin.java

private boolean buildTabs(ActionBar bar, JSONArray definition, String menu_var) {
    try {/*ww  w .  j  a  v a  2s  . c om*/
        for (int i = 0; i < definition.length(); ++i) {
            final JSONObject item_def = definition.getJSONObject(i);
            final String text = item_def.isNull("text") ? "" : item_def.getString("text");
            final Drawable icon = item_def.isNull("icon") ? null
                    : getDrawableForURI(item_def.getString("icon"));

            bar.addTab(bar.newTab().setText(text).setIcon(icon)
                    .setTabListener(new TabListener(this, menu_var + "[" + i + "]")));
        }
    } catch (JSONException e) {
        return false;
    }

    return true;
}

From source file:menusearch.json.JSONProcessor.java

/**
 * //  w  w  w.  j a va  2 s  .  c  o m
 * @param json formated JSON string containing all the information for one recipe
 * @return Recipe object
 * @throws IOException 
 * 
 * This method takes a formated json string containing one recipe, parses it, and saves it into a recipe object which is then returned. 
 * **You must call the getRecipeAPI() method prior to calling this method.
 */
public static Recipe parseRecipe(String json) throws IOException, JSONException {

    JSONTokener tokenizer = new JSONTokener(json);
    JSONObject obj = new JSONObject(tokenizer);
    Recipe r = new Recipe();

    JSONObject attribution = obj.getJSONObject("attribution");
    Attribution a = new Attribution();
    a.setHTML(attribution.getString("html"));
    a.setUrl(attribution.getString("url"));
    a.setText(attribution.getString("text"));
    a.setLogo(attribution.getString("logo"));
    r.setAttribution(a);

    JSONArray ingredientList = obj.getJSONArray("ingredientLines");
    for (int i = 0; i < ingredientList.length(); i++) {
        r.addIngredient(ingredientList.getString(i));
    }

    JSONObject flavors = obj.getJSONObject("flavors");
    r.setBitterFlavor(flavors.getDouble("Bitter"));
    r.setMeatyFlavor(flavors.getDouble("Meaty"));
    r.setPiquantFlavor(flavors.getDouble("Piquant"));
    r.setSaltyFlavor(flavors.getDouble("Salty"));
    r.setSourFlavor(flavors.getDouble("Sour"));
    r.setSweetFlavor(flavors.getDouble("Sweet"));

    JSONArray nutritionEstimates = obj.getJSONArray("nutritionEstimates");
    for (int i = 0; i < nutritionEstimates.length(); i++) {
        NutritionEstimate nutritionInfo = new NutritionEstimate();
        Unit aUnit = new Unit();

        JSONObject nutrition = nutritionEstimates.getJSONObject(i);
        nutritionInfo.setAttribute(nutrition.getString("attribute"));

        if (nutrition.isNull("description") != true)
            nutritionInfo.setDescription(nutrition.getString("description"));
        nutritionInfo.setValue(nutrition.getDouble("value"));

        JSONObject unit = nutrition.getJSONObject("unit");
        aUnit.setAbbreviation(unit.getString("abbreviation"));
        aUnit.setName(unit.getString("name"));
        aUnit.setPlural(unit.getString("plural"));
        aUnit.setPluralAbbreviation(unit.getString("pluralAbbreviation"));

        nutritionInfo.addUnit(aUnit);

        r.addNutritionInfo(nutritionInfo);

    }
    JSONArray images = obj.getJSONArray("images");

    JSONObject imageBySize = images.getJSONObject(0);

    for (int i = 0; i < images.length(); i++) {
        if (images.getJSONObject(i).has("hostedLargeUrl"))
            r.setHostedlargeUrl(images.getJSONObject(i).getString("hostedLargeUrl"));
        if (images.getJSONObject(i).has("hostedMediumUrl"))
            r.setHostedMediumUrl(images.getJSONObject(i).getString("hostedMediumUrl"));
        if (images.getJSONObject(i).has("hostedSmallUrl"))
            r.setHostedSmallUrl(images.getJSONObject(i).getString("hostedSmallUrl"));
    }

    if (obj.has("name"))
        r.setName(obj.getString("name"));

    if (obj.has("yield"))
        r.setYield(obj.getString("yield"));

    if (obj.has("totalTime"))
        r.setTotalTime(obj.getString("totalTime"));

    if (obj.has("attributes")) {
        JSONObject attributes = obj.getJSONObject("attributes");
        if (attributes.has("holiday")) {
            JSONArray holidays = attributes.getJSONArray("holiday");
            for (int i = 0; i < holidays.length(); i++) {
                r.addholidayToList(holidays.getString(i));
            }
        }
        if (attributes.has("cuisine")) {
            JSONArray cuisine = attributes.getJSONArray("cuisine");
            for (int i = 0; i < cuisine.length(); i++) {
                r.addCuisineToList(cuisine.getString(i));
            }
        }
    }
    if (obj.has("totalTimeInSeconds"))
        r.setTimetoCook(obj.getDouble("totalTimeInSeconds"));

    if (obj.has("rating"))
        r.setRating(obj.getDouble("rating"));

    if (obj.has("numberofServings"))
        r.setNumberOfServings(obj.getDouble("numberOfServings"));

    if (obj.has("source")) {
        JSONObject source = obj.getJSONObject("source");

        if (source.has("sourceSiteUrl"))
            r.setSourceSiteUrl(source.getString("sourceSiteUrl"));

        if (source.has("sourceRecipeUrl"))
            r.setSourceRecipeUrl(source.getString("sourceRecipeUrl"));

        if (source.has("sourceDisplayName"))
            r.setSourceDisplayName(source.getString("sourceDisplayName"));
    }
    r.setRecipeID(obj.getString("id"));

    return r;

}