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.github.socialc0de.gsw.android.MainActivity.java

public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<String, Object>();

    Iterator<String> keysItr = object.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();
        Object value = object.get(key);

        if (value instanceof JSONArray) {
            value = toList((JSONArray) value);
        } else if (value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }//from ww  w .  j  a  v a2 s. c  o m
        map.put(key, value);
    }
    return map;
}

From source file:com.github.socialc0de.gsw.android.MainActivity.java

public HashMap<String, Category> parseCat(String json) {
    try {//ww w.j a  va2 s. co m
        JSONObject cat_json = new JSONObject(json);
        HashMap<String, Category> map = new HashMap<String, Category>();

        Iterator<String> keysItr = cat_json.keys();
        while (keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = cat_json.get(key);
            Category cat = new Category();
            if (value instanceof JSONObject) {
                JsonFactory factory = new AndroidJsonFactory();
                cat = factory.fromString(value.toString(), Category.class);
            }
            map.put(key, cat);
        }
        return map;
    } catch (Exception e) {
        Log.d(TAG, "Error", e);
        return null;
    }
}

From source file:de.hackerspacebremen.format.JSONFormatter.java

@Override
public T reformat(final String object, final Class<T> entityClass) throws FormatException {
    T result = null;//w w  w  .  j a  v  a 2  s  .co  m
    final Map<String, Field> fieldMap = new HashMap<String, Field>();
    if (entityClass.isAnnotationPresent(Entity.class)) {
        final Field[] fields = entityClass.getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(FormatPart.class)) {
                fieldMap.put(field.getAnnotation(FormatPart.class).key(), field);
            }
        }
        try {
            final JSONObject json = new JSONObject(object);
            result = entityClass.newInstance();
            for (final String key : fieldMap.keySet()) {
                if (json.has(key)) {
                    final Field field = fieldMap.get(key);
                    final Method method = entityClass.getMethod(this.getSetter(field.getName()),
                            new Class<?>[] { field.getType() });

                    final String type = field.getType().toString();
                    if (type.equals("class com.google.appengine.api.datastore.Key")) {
                        method.invoke(result, KeyFactory.stringToKey(json.getString(key)));
                    } else if (type.equals("class com.google.appengine.api.datastore.Text")) {
                        method.invoke(result, new Text(json.getString(key)));
                    } else if (type.equals("boolean")) {
                        method.invoke(result, json.getBoolean(key));
                    } else if (type.equals("long")) {
                        method.invoke(result, json.getLong(key));
                    } else if (type.equals("int")) {
                        method.invoke(result, json.getInt(key));
                    } else {
                        method.invoke(result, json.get(key));
                    }
                }
            }
        } catch (JSONException e) {
            logger.warning("JSONException occured: " + e.getMessage());
            throw new FormatException();
        } catch (NoSuchMethodException e) {
            logger.warning("NoSuchMethodException occured: " + e.getMessage());
            throw new FormatException();
        } catch (SecurityException e) {
            logger.warning("SecurityException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalAccessException e) {
            logger.warning("IllegalAccessException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalArgumentException e) {
            logger.warning("IllegalArgumentException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InvocationTargetException e) {
            logger.warning("InvocationTargetException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InstantiationException e) {
            logger.warning("InstantiationException occured: " + e.getMessage());
            throw new FormatException();
        }
    }
    return result;
}

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

/**
 * Creates the algo control list./*from  w  ww.j a v a2 s .c o m*/
 * @param jobData the job data
 * @param thermostatId the thermostat id
 * @param algoId the algo id
 * @return the list
 */
protected List<ThermostatAlgorithmController> createAlgoControlList(JSONArray jobData, Integer thermostatId,
        Integer algoId) {

    Algorithm algorithm = findByAlgorithmId(algoId);
    List<ThermostatAlgorithmController> algoControlList = new ArrayList<ThermostatAlgorithmController>();

    int moBlackOut;
    double moRecovery;
    double deltaEE = 0;
    Calendar utcCalendar = null;
    Calendar startTime = null;
    Calendar endTime = null;
    Calendar moCutoffTime = null;
    JSONObject jsonObj;

    for (int i = 0; i < jobData.length(); i++) {

        try {

            jsonObj = jobData.getJSONObject(i);
            startTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("start"));
            endTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("end"));
            moCutoffTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("moCutoff"));

            moBlackOut = jsonObj.getInt("moBlackOut");
            moRecovery = jsonObj.getInt("moRecovery");
            deltaEE = jsonObj.getDouble("deltaEE");

            ThermostatAlgorithmController algoControlPhase1 = new ThermostatAlgorithmController();
            algoControlPhase1.setStatus(Status.ACTIVE);
            algoControlPhase1.setThermostatId(thermostatId);
            algoControlPhase1.setAlgorithmId(algoId);

            String utcCalendarTimeStamp = DateUtil.format(startTime, DateUtil.DATE_FMT_FULL);
            utcCalendar = DateUtil.parseToCalendar(utcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            // Next phase time
            algoControlPhase1.setNextPhaseTime(utcCalendar);

            // Execution start time.
            Calendar executionStartTime = (Calendar) utcCalendar.clone();
            executionStartTime.add(Calendar.MINUTE, -3);
            algoControlPhase1.setExecutionStartTimeUTC(executionStartTime);

            String endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL);
            Calendar endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            // Execution end time.
            algoControlPhase1.setExecutionEndTimeUTC(endutcCalendar);

            String cuttoffutcCalendarTimeStamp = DateUtil.format(moCutoffTime, DateUtil.DATE_FMT_FULL);
            Calendar cutOffutcCalendar = DateUtil.parseToCalendar(cuttoffutcCalendarTimeStamp,
                    DateUtil.DATE_FMT_FULL);

            // MO cut off time.
            algoControlPhase1.setMoCutOff(cutOffutcCalendar);

            algoControlPhase1.setPhase0Spt(deltaEE);
            algoControlPhase1.setPrevSpt(0.0);
            algoControlPhase1.setMoBlackOut(moBlackOut);
            algoControlPhase1.setMoRecovery(moRecovery);
            algoControlPhase1.setAlgorithm(algorithm);
            if (algoId == SPO_COOL || algoId == SPO_HEAT) {
                algoControlPhase1.setActor(ACTOR_SPO);
            }

            algoControlList.add(algoControlPhase1);
            // second row
            ThermostatAlgorithmController algoControlPhase2 = new ThermostatAlgorithmController();

            algoControlPhase2 = algoControlPhase1.clone();

            endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL);
            endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            if (algoId == SPO_COOL || algoId == SPO_HEAT) {
                algoControlPhase2.setActor(ACTOR_SPO);
            }
            // Execution end time.
            algoControlPhase2.setExecutionStartTimeUTC(endutcCalendar);
            algoControlPhase2.setExecutionEndTimeUTC(null);
            algoControlPhase2.setNextPhaseTime(endutcCalendar);
            algoControlPhase2.setPhase0Spt(0.0);
            algoControlPhase2.setAlgorithm(algorithm);
            algoControlPhase2.setStatus(Status.ACTIVE);
            algoControlList.add(algoControlPhase2);

        } catch (JSONException | CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
    return algoControlList;
}

From source file:br.com.hslife.orcamento.json.TestJson1.java

@Test
public void readJsonValues() {
    Usuario usuario = new Usuario();
    usuario.setId(10l);/*from   w ww  . j  a va2s .c o  m*/

    Categoria categoria = new Categoria();
    categoria.setAtivo(true);
    categoria.setDescricao("Categoria de teste");
    categoria.setId(100l);
    categoria.setPadrao(false);
    categoria.setTipoCategoria(TipoCategoria.DEBITO);
    categoria.setUsuario(usuario);

    JSONObject json = new JSONObject();

    for (String s : categoria.getFieldValues().keySet()) {
        json.put(s, categoria.getFieldValues().get(s));
    }

    JSONObject jsonRead = new JSONObject(json.toString());

    System.out.println("JSON lido ->  " + jsonRead.toString());

    for (Object obj : jsonRead.keySet()) {
        System.out.println("Chave: " + obj + "; valor: " + jsonRead.get((String) obj));
    }
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Object[][] getLatestTorrentsWithDetails(int set, int limit)
        throws JSONException, IOException, MalformedURLException, NoSuchAlgorithmException {
    Object[][] o = new Object[limit][2];
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;
    jSONObject = jsonReader.readJsonFromUrl(
            "http://ytsre.eu/api/list.json?set=" + Integer.toString(set) + "&limit=" + Integer.toString(limit));
    if (jSONObject.has("status")) {
        if (jSONObject.get("status").equals("fail")) {
            o = null;//w  w  w .  j  av  a  2 s .  c o  m
        }
    } else {
        JSONArray jSONArray = (JSONArray) jSONObject.get("MovieList");
        for (int i = 0; i < jSONArray.length(); i++) {
            JSONObject jsono = (JSONObject) jSONArray.get(i);
            int torrentID = Integer.parseInt(jsono.get("MovieID").toString());
            String imdbCode = jsono.get("ImdbCode").toString();
            o[i][0] = getTorrentDetails(torrentID);
            o[i][1] = imdbCode;
        }
    }
    return o;
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Object[][] getVideosAndTorrentsFromLatestTorrentsWithDetails(int set, int limit)
        throws ParseException, IOException, JSONException, MalformedURLException, NoSuchAlgorithmException {
    Object[][] o = new Object[limit][2];
    Collection<Torrent> torrentCollection = null;
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;
    jSONObject = jsonReader.readJsonFromUrl(
            "http://ytsre.eu/api/list.json?set=" + Integer.toString(set) + "&limit=" + Integer.toString(limit));
    JSONArray jSONArray = (JSONArray) jSONObject.get("MovieList");
    for (int i = 0; i < jSONArray.length(); i++) {
        JSONObject jsono = (JSONObject) jSONArray.get(i);
        IMDBGraber imdbg = new IMDBGraber();
        String imdbCode = jsono.get("ImdbCode").toString();
        torrentCollection = getAllTorrentsFromVideo(imdbCode);
        Video video = imdbg.getVideo(imdbCode);
        o[i][0] = video;//from w ww  .  ja v a 2  s.c  o m
        o[i][1] = torrentCollection;
    }
    return o;
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Torrent getTorrentDetails(int id)
        throws NoSuchAlgorithmException, MalformedURLException, JSONException, IOException {
    Torrent torrent;//from  ww w  . j  a v a2s  . c  o  m
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;
    jSONObject = jsonReader.readJsonFromUrl("http://ytsre.eu/api/movie.json?id=" + Integer.toString(id));
    torrent = new Torrent();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    try {
        torrent.setDateUploaded(dateFormat.parse(jSONObject.get("DateUploaded").toString()));
    } catch (ParseException ex) {
        Logger.getLogger(YIFYGraber.class.getName()).log(Level.SEVERE, null, ex);
    }
    torrent.setQuality(jSONObject.get("Quality").toString());
    torrent.setSize(jSONObject.get("Size").toString());
    torrent.setTorrentSeeds(Integer.parseInt(jSONObject.get("TorrentSeeds").toString()));
    torrent.setTorrentPeers(Integer.parseInt(jSONObject.get("TorrentPeers").toString()));
    torrent.setMagnetURL(jSONObject.get("TorrentMagnetUrl").toString());
    URL torrentUrl = null;
    torrentUrl = new URL(jSONObject.get("TorrentUrl").toString());
    byte[] torrentFile = null;
    torrentFile = Downloader.getAsByteArray(torrentUrl);
    torrent.setTorrentFile(torrentFile);
    String checksum = "";
    checksum = Downloader.SHAsum(torrentFile);
    Collection<Screenshot> screenshotCollection = new ArrayList<>();
    int k = 1;
    while (true) {
        URL screenshotURL = null;
        if (jSONObject.has("MediumScreenshot" + Integer.toString(k))) {
            screenshotURL = new URL(jSONObject.get("MediumScreenshot" + Integer.toString(k)).toString());
        } else {
            break;
        }
        byte[] screenshotFile = null;
        screenshotFile = Downloader.getAsByteArray(screenshotURL);
        Screenshot screenshot = new Screenshot();
        screenshot.setTorrentID(torrent);
        screenshot.setPicture(screenshotFile);
        screenshotCollection.add(screenshot);
        k++;
    }
    torrent.setScreenshotCollection(screenshotCollection);
    torrent.setChecksum(checksum);
    torrent.setDistributor("yify");
    return torrent;
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Collection<Torrent> getAllTorrentsFromVideo(String imdbCode)
        throws JSONException, IOException, MalformedURLException, NoSuchAlgorithmException {
    Collection<Torrent> torrentCollection = null;
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;
    jSONObject = jsonReader.readJsonFromUrl("http://ytsre.eu/api/listimdb.json?imdb_id=" + imdbCode);

    torrentCollection = new ArrayList<>();
    JSONArray jSONArray = (JSONArray) jSONObject.get("MovieList");
    for (int i = 0; i < jSONArray.length(); i++) {
        JSONObject json = (JSONObject) jSONArray.get(i);
        torrentCollection.add(getTorrentDetails(Integer.parseInt(json.get("MovieID").toString())));
    }//from w  ww .j  a  va 2 s  .c om
    return torrentCollection;
}

From source file:org.collectionspace.chain.csp.persistence.services.TestPermissions.java

@Test
public void testRoles() throws Exception {
    //create user
    JSONObject userdata = createUser("user1.json");
    String userId = userdata.getString("userId");
    String csidId = userdata.getString("accountId");
    assertFalse(userdata == null);//from   w  w  w.j  a  v  a 2  s  .c o m

    //list roles for user
    //cspace-services/authorization/roles/{csid}/permroles/xxx

    Storage ss;
    ss = makeServicesStorage();
    JSONObject data = ss.getPathsJSON("accounts/" + userId + "/accountrole", null);
    String[] roleperms = (String[]) data.get("listItems");
    log.info(data.toString());

    if (roleperms.length > 0) {
        log.info("has roles already");
    }

    //create a role
    JSONObject roledata = createRole("role.json");
    String role = roledata.getString("roleId");
    log.info(roledata.toString());
    assertFalse(roledata == null);

    //add a role
    JSONObject addroledata = new JSONObject();
    addroledata.put("roleId", role);
    addroledata.put("roleName", roledata.getString("roleName"));
    JSONArray rolearray = new JSONArray();
    rolearray.put(addroledata);

    JSONObject addrole = new JSONObject();
    addrole.put("role", rolearray);
    addrole.put("account", userdata);

    log.info(addrole.toString());
    //add permissions to role

    String path = ss.autocreateJSON("userrole", addrole, null);
    log.info(path);
    assertNotNull(path);

    //delete role
    ss.deleteJSON("role/" + role);
    try {
        ss.retrieveJSON("role/" + role, new JSONObject());
        assertFalse(true); // XXX use JUnit exception annotation
    } catch (UnderlyingStorageException e) {
        assertTrue(true); // XXX use JUnit exception annotation
    }

    //delete user
    ss.deleteJSON("users/" + csidId);

}