Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Checks if is sPO block active./*from ww w.j a  v a  2  s . c o  m*/
 * 
 * @param thermostatId
 *            the thermostat id
 * @param algoId
 *            the algo id
 * @return true, if is sPO block active
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#isSPOBlockActive(java.lang.Integer,
 *      int)
 */
@Override
public boolean isSPOBlockActive(Integer thermostatId, int algoId) {

    log("Check if SPO is active for thermostat :" + thermostatId, true);
    boolean spoActive = false;
    Thermostat thermostat = findBythermostatId(thermostatId);
    Calendar currentTime = (Calendar) Calendar.getInstance(TimeZone.getTimeZone(thermostat.getTimezone()))
            .clone();

    JSONArray jsonArray = getJobData(thermostatId);
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            Calendar startCal = DateUtil.getTimeZoneCalendar((String) jsonObj.get("start"),
                    thermostat.getTimezone());
            Calendar endcal = DateUtil.getTimeZoneCalendar((String) jsonObj.get("end"),
                    thermostat.getTimezone());

            if (currentTime.after(startCal) && currentTime.before(endcal)) {
                spoActive = true;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return spoActive;
}

From source file:org.everit.json.schema.IssueTest.java

private void readExpectedValues(final JSONObject expected) {
    expectedFailureList.add((String) expected.get("message"));
    if (expected.has("causingExceptions")) {
        JSONArray causingEx = expected.getJSONArray("causingExceptions");
        for (Object subJson : causingEx) {
            readExpectedValues((JSONObject) subJson);
        }//from  www  .j  a  va 2  s  .  co m
    }
}

From source file:com.pansapiens.occyd.JSONdecoder.java

/**
* Abstract utility class for parsing JSON objects (as strings) and
* returning Java objects./*  w  w w .j a va  2 s.  c  om*/
*/
public static ArrayList<Post> json2postArray(String json_txt) throws JSONException {
    /**
     * Takes an appropriate JSON format string, returned as a response
     * by the server to a search query, returns an ArrayList
     *  of Post objects. 
     */
    ArrayList<Post> post_results = new ArrayList();

    if (json_txt != null) {
        // http://code.google.com/android/reference/org/json/JSONObject.html
        JSONTokener jsontok = new JSONTokener(json_txt);
        JSONObject json;
        String geohash = null;
        String[] tags = null;

        // TODO: read these from the JSON too
        //String key = null;
        //String user = null;
        //String desc = null;
        //URL link = null;
        // see: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html
        //Date date = null;
        // parse "2008-12-31 03:22:23.350798" format date with:
        // (could have an issue with to many millisecond places SSSSSS .... may need to truncate)
        // SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        // Date date = dateformat.parse(dateString);

        float lat, lon;

        json = new JSONObject(jsontok);

        // catch any error codes in the returned json
        String result = json.getString("result");
        if (!result.equals("done")) {
            return post_results;
        }

        // unpack the json into Post objects, add them to the result list
        JSONArray posts = json.getJSONArray("posts");
        for (int i = 0; i < posts.length(); i++) {
            JSONObject p = posts.getJSONObject(i);
            geohash = (String) p.get("geohash");
            JSONArray coordinates = p.getJSONArray("coordinates");
            lat = (float) coordinates.getDouble(0);
            lon = (float) coordinates.getDouble(1);

            JSONArray t = p.getJSONArray("tags");
            tags = new String[t.length()];
            for (int j = 0; j < t.length(); j++) {
                tags[j] = t.getString(j);
            }

            Post post = new Post(lat, lon, geohash, tags);
            post_results.add(post);
        }
    }
    return post_results;
}

From source file:com.scvngr.levelup.core.net.request.factory.ClaimRequestFactoryTest.java

@SmallTest
public void testBuildClaimLegacyLoyaltyRequest() throws BadRequestException, JSONException {
    final String loyaltyId = "2222";
    final LevelUpRequest request = (LevelUpRequest) new ClaimRequestFactory(getContext(),
            new MockAccessTokenRetriever()).buildClaimLegacyLoyaltyRequest(1, loyaltyId);

    assertEquals(HttpMethod.POST, request.getMethod());
    final JSONObject object = new JSONObject(request.getBody(getContext()))
            .getJSONObject(ClaimRequestFactory.OUTER_PARAM_LEGACY_LOYALTY);
    assertTrue(object.has(ClaimRequestFactory.PARAM_LEGACY_ID));
    assertEquals(loyaltyId, object.get(ClaimRequestFactory.PARAM_LEGACY_ID));
    assertFalse(0 == request.getBodyLength(getContext()));

    final URL url = request.getUrl(getContext());
    assertNotNull(url);//from  w w  w  . j a  v  a  2  s. c o  m
    // Make sure we hit the proper API version and url.
    assertEquals("/v15/loyalties/legacy/1/claims", url.getPath());
}

From source file:com.facebook.android.Facebook.java

/**
 * This function does the heavy lifting of publishing an install.
 * @param fb//from  www  . j av a  2 s.c  om
 * @param applicationId
 * @param context
 * @throws Exception
 */
private static void publishInstall(final Facebook fb, final String applicationId, final Context context)
        throws JSONException, FacebookError, MalformedURLException, IOException {

    String attributionId = Facebook.getAttributionId(context.getContentResolver());
    SharedPreferences preferences = context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE);
    String pingKey = applicationId + "ping";
    long lastPing = preferences.getLong(pingKey, 0);
    if (lastPing == 0 && attributionId != null) {
        Bundle supportsAttributionParams = new Bundle();
        supportsAttributionParams.putString(APPLICATION_FIELDS, SUPPORTS_ATTRIBUTION);
        JSONObject supportResponse = Util.parseJson(fb.request(applicationId, supportsAttributionParams));
        Object doesSupportAttribution = (Boolean) supportResponse.get(SUPPORTS_ATTRIBUTION);

        if (!(doesSupportAttribution instanceof Boolean)) {
            throw new JSONException(String.format("%s contains %s instead of a Boolean", SUPPORTS_ATTRIBUTION,
                    doesSupportAttribution));
        }

        if ((Boolean) doesSupportAttribution) {
            Bundle publishParams = new Bundle();
            publishParams.putString(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT);
            publishParams.putString(ATTRIBUTION_KEY, attributionId);

            String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId);

            fb.request(publishUrl, publishParams, "POST");

            // denote success since no error threw from the post.
            SharedPreferences.Editor editor = preferences.edit();
            editor.putLong(pingKey, System.currentTimeMillis());
            editor.commit();
        }
    }
}

From source file:id.co.nlp.MachineTranslationAPP.FormTraining.java

private void trainingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trainingButtonActionPerformed
    if (this.sourceFile.isEmpty() || this.targetFile.isEmpty() || this.dictFile.isEmpty()) {
        JOptionPane.showMessageDialog(this, "data yang anda masukan kurang lengkap");
    } else {//from   w w  w  .  jav  a2  s.co m
        try {
            long startTime = System.currentTimeMillis();
            this.machineTranslation.training(Util.read(this.sourceFile).toLowerCase(),
                    Util.read(this.targetFile).toLowerCase(), this.dictFile, 2, true);
            new File(System.getProperty("user.home") + File.separator + ".machine_translation").mkdirs();
            this.machineTranslation
                    .save(System.getProperty("user.home") + File.separator + ".machine_translation");
            long endTime = System.currentTimeMillis();
            JSONObject timeProcess = this.getTimeProcess(endTime - startTime);
            this.resultLabel.setText("Pelatihan Selesai dengan waktu pelatihan " + timeProcess.get("hours")
                    + " jam, " + timeProcess.get("minutes") + " menit, " + timeProcess.get("second")
                    + " detik, " + timeProcess.get("milisecond") + " milisecon");
            JOptionPane.showMessageDialog(this, "training selesai");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
            Logger.getLogger(FormTraining.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java

/**
 * Main method to decode a GeoJSON String
 * //from  w  ww  . j a v a2s  .  c o  m
 * @param s
 *            The string in GeoJSON format
 * @return if the paramater has inside a FeatureCollection tag, the method
 *         will the decode the GeoJSON String and it will return a
 *         FeatureCollection otherwise, it will return null;
 * @throws JSONException
 */
public FeatureCollection decode(String s) throws JSONException {
    JSONTokener tokener = new JSONTokener(s);

    JSONObject o = new JSONObject(tokener);
    if (o.get("type").equals("FeatureCollection")) {
        return this.decodeFeatureCollection(o);
    } else {
        // TODO
        // throw exception
        return null;
    }

}

From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java

private FeatureCollection decodeFeatureCollection(JSONObject object) throws JSONException {

    FeatureCollection fCollection = null;

    JSONArray array = object.getJSONArray("features");
    if (array != null) {
        fCollection = new FeatureCollection();
        for (int i = 0; i < array.length(); i++) {
            JSONObject o = array.getJSONObject(i);
            if (o.get("type").equals("Feature")) {
                Feature f = this.decodeFeature(o);
                fCollection.addFeature(f);
            }//w  ww .j a  va2 s. c  om
        }
    }

    return fCollection;
}

From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java

private IGeometry decodeGeometry(JSONObject object) throws JSONException {
    IGeometry geom = null;//from w w  w.  j a v a2  s .  c om
    LineString[] lineStrings;
    if (object.get("type").equals("MultiLineString")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        int size = coordinates.length();
        lineStrings = new LineString[size];
        LineString l;
        for (int i = 0; i < size; i++) {
            JSONArray lineStrCoord = coordinates.getJSONArray(i);
            double[][] coords = this.decodeLineStringCoords(lineStrCoord);
            l = new LineString(coords[0], coords[1]);
            lineStrings[i] = l;
        }

        geom = new MultiLineString(lineStrings);
    } else if (object.get("type").equals("LineString")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        double[][] coords = this.decodeLineStringCoords(coordinates);
        geom = new LineString(coords[0], coords[1]);
    } else if (object.get("type").equals("Point")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        geom = new Point(coordinates.getDouble(0), coordinates.getDouble(1));
    } else if (object.get("type").equals("Polygon")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        double[][] coords = this.decodeLineStringCoords(coordinates);
        geom = new Polygon(coords[0], coords[1]);
    }

    return geom;
}

From source file:org.jabsorb.ng.serializer.impl.DictionarySerializer.java

@Override
public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONObject jso = (JSONObject) o;
    String java_class;

    // Hint presence
    try {//from  w w w  .j  a  va2 s.  c  o  m
        java_class = jso.getString("javaClass");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read javaClass", e);
    }
    if (java_class == null) {
        throw new UnmarshallException("no type hint");
    }

    // Class compatibility check
    if (!classNameCheck(java_class)) {
        throw new UnmarshallException("not a Dictionary");
    }

    // JSON Format check
    JSONObject jsonmap;
    try {
        jsonmap = jso.getJSONObject("map");
    } catch (final JSONException e) {
        throw new UnmarshallException("map missing", e);
    }
    if (jsonmap == null) {
        throw new UnmarshallException("map missing");
    }

    // Content check
    final ObjectMatch m = new ObjectMatch(-1);
    state.setSerialized(o, m);

    final Iterator<?> i = jsonmap.keys();
    String key = null;
    try {
        while (i.hasNext()) {
            key = (String) i.next();
            m.setMismatch(ser.tryUnmarshall(state, null, jsonmap.get(key)).max(m).getMismatch());
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    }

    return m;
}