Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:de.dakror.virtualhub.data.Catalog.java

public Catalog(JSONObject o) {
    try {/*from  w  w w  . jav  a 2  s.  co m*/
        name = o.getString("name");

        JSONArray sources = o.getJSONArray("sources");
        for (int i = 0; i < sources.length(); i++)
            this.sources.add(new File(sources.getString(i)));

        JSONArray tags = o.getJSONArray("tags");
        for (int i = 0; i < tags.length(); i++)
            this.tags.add(tags.getString(i));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:tom.udacity.sample.sunrise.WeatherDataParser.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//from ww  w  . j  a  v  a 2  s  .c o  m
 */
public String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationQuery)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DATETIME = "dt";
    final String OWM_DESCRIPTION = "main";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    String[] resultStrs = new String[numDays];
    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format "Day, description, hi/low"
        String day;
        String description;
        String highAndLow;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        long dateTime = dayForecast.getLong(OWM_DATETIME);
        day = getReadableDateString(dateTime);

        // description is in a child array called "weather", which is 1 element long.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);

        highAndLow = formatHighLows(high, low);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    return resultStrs;
}

From source file:tom.udacity.sample.sunrise.WeatherDataParser.java

/**
 * Given a string of the form returned by the api call:
 * http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
 * retrieve the maximum temperature for the day indicated by dayIndex
 * (Note: 0-indexed, so 0 would refer to the first day).
 *///from   w  ww  .  j av  a 2  s  .c om
private static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex) throws JSONException {
    JSONObject data = new JSONObject(weatherJsonStr);
    JSONArray days = data.getJSONArray("list");
    JSONObject dayJson = days.getJSONObject(dayIndex);
    JSONObject temp = dayJson.getJSONObject("temp");
    return temp.getDouble("max");
}

From source file:edu.umass.cs.gigapaxos.paxospackets.FindReplicaGroupPacket.java

public FindReplicaGroupPacket(JSONObject msg) throws JSONException {
    super(msg);//from   w ww.  j  a va2 s  .c  om
    this.packetType = PaxosPacketType.FIND_REPLICA_GROUP;
    this.nodeID = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString());
    JSONArray jsonGroup = null;
    if (msg.has(PaxosPacket.NodeIDKeys.GROUP.toString())) {
        jsonGroup = msg.getJSONArray(PaxosPacket.NodeIDKeys.GROUP.toString());
    }
    if (jsonGroup != null && jsonGroup.length() > 0) {
        this.group = new int[jsonGroup.length()];
        for (int i = 0; i < jsonGroup.length(); i++) {
            this.group[i] = Integer.valueOf(jsonGroup.getString(i));
        }
    } else
        this.group = null;
}

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

public BayeuxMessage(String jsonMessage) throws JSONException {
    JSONTokener jsont = new JSONTokener(jsonMessage);
    JSONArray jsona = new JSONArray(jsont);
    // FIXME ? msg   .
    JSONObject jsono = jsona.getJSONObject(0);
    // channel //from   w w  w . j av a 2  s. c o  m
    channel = jsono.getString("channel");
    if (channel != null && channel.startsWith("/meta/")) {
        if ("/meta/handshake".equals(channel)) {
            // type 
            type = BayeuxMessage.HANDSHAKE_REQ;
            // version 
            version = jsono.getString("version");
            JSONArray jsonaSupportedConnectionTypes = jsono.getJSONArray("supportedConnectionTypes");
            supportedConnectionTypesList = new ArrayList<String>();
            // supportedConnectionTypes 
            for (int i = 0; i < jsonaSupportedConnectionTypes.length(); i++) {
                supportedConnectionTypesList.add(jsonaSupportedConnectionTypes.getString(i));
            }
            // Handshake req ?  mandatory ? ? ?.
        } else if ("/meta/connect".equals(channel)) {
            type = BayeuxMessage.CONNECT_REQ;
            clientId = jsono.getString("clientId");
            connectionType = jsono.getString("connectionType");
        } else if ("/meta/disconnect".equals(channel)) {
            type = BayeuxMessage.DISCONNECT_REQ;
            clientId = jsono.getString("clientId");
        } else if ("/meta/subscribe".equals(channel)) {
            type = BayeuxMessage.SUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        } else if ("/meta/unsubscribe".equals(channel)) {
            type = BayeuxMessage.UNSUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        }
    } else {
        type = BayeuxMessage.PUBLISH_REQ;
        data = jsono.getString("data");
    }
}

From source file:com.trellmor.berrytube.BerryTubeIOCallback.java

/**
 * @see io.socket.IOCallback#on(java.lang.String, io.socket.IOAcknowledge,
 *      java.lang.Object[])/*from w  ww . ja va  2  s.  c o m*/
 */
public void on(String event, IOAcknowledge ack, Object... args) {
    if (event.compareTo("chatMsg") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject jsonMsg = (JSONObject) args[0];

            try {
                berryTube.getHandler()
                        .post(berryTube.new ChatMsgTask(new ChatMessage(jsonMsg.getJSONObject("msg"))));
            } catch (JSONException e) {
                Log.e(TAG, "chatMsg", e);
            }
        } else
            Log.w(TAG, "chatMsg message is not a JSONObject");
    } else if (event.compareTo("setNick") == 0) {
        if (args.length >= 1 && args[0] instanceof String) {
            berryTube.getHandler().post(berryTube.new SetNickTask((String) args[0]));
        } else
            Log.w(TAG, "setNick message is not a String");
    } else if (event.compareTo("loginError") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject error = (JSONObject) args[0];
            berryTube.getHandler()
                    .post(berryTube.new LoginErrorTask(error.optString("message", "Login failed")));
        }
    } else if (event.compareTo("userJoin") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_JOIN));
            } catch (JSONException e) {
                Log.e(TAG, "userJoin", e);
            }
        } else
            Log.w(TAG, "userJoin message is not a JSONObject");
    } else if (event.compareTo("newChatList") == 0) {
        berryTube.getHandler().post(berryTube.new UserResetTask());
        if (args.length >= 1 && args[0] instanceof JSONArray) {
            JSONArray users = (JSONArray) args[0];
            for (int i = 0; i < users.length(); i++) {
                JSONObject user = users.optJSONObject(i);
                if (user != null) {
                    try {
                        berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                                BerryTube.UserJoinPartTask.ACTION_JOIN));
                    } catch (JSONException e) {
                        Log.e(TAG, "newChatList", e);
                    }
                }
            }
        } else
            Log.w(TAG, "newChatList message is not a JSONArray");
    } else if (event.compareTo("userPart") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_PART));
            } catch (JSONException e) {
                Log.e(TAG, "userPart", e);
            }
        } else
            Log.w(TAG, "userPart message is not a JSONObject");
    } else if (event.compareTo("drinkCount") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject drinks = (JSONObject) args[0];
            berryTube.getHandler().post(berryTube.new DrinkCountTask(drinks.optInt("drinks")));
        }
    } else if (event.compareTo("kicked") == 0) {
        berryTube.getHandler().post(berryTube.new KickedTask());
    } else if (event.compareTo("newPoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            ChatMessage msg;

            // Send chat message for new poll
            try {
                msg = new ChatMessage(poll.getString("creator"), poll.getString("title"),
                        ChatMessage.EMOTE_POLL, 0, 0, false, 1);
                berryTube.getHandler().post(berryTube.new ChatMsgTask(msg));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }

            // Create new poll
            try {
                berryTube.getHandler().post(berryTube.new NewPollTask(new Poll(poll)));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }
        }
    } else if (event.compareTo("updatePoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            try {
                JSONArray votes = poll.getJSONArray("votes");
                int[] voteArray = new int[votes.length()];
                for (int i = 0; i < votes.length(); i++) {
                    voteArray[i] = votes.optInt(i, -1);
                }
                berryTube.getHandler().post(berryTube.new UpdatePollTask(voteArray));
            } catch (JSONException e) {
                Log.e(TAG, "updatePoll", e);
            }
        }
    } else if (event.compareTo("clearPoll") == 0) {
        berryTube.getHandler().post(berryTube.new ClearPollTask());
    } else if (event.compareTo("forceVideoChange") == 0 || event.compareTo("hbVideoDetail") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject videoMsg = (JSONObject) args[0];
            try {
                JSONObject video = videoMsg.getJSONObject("video");
                String name = URLDecoder.decode(video.getString("videotitle"), "UTF-8");
                String id = video.getString("videoid");
                String type = video.getString("videotype");
                berryTube.getHandler().post(berryTube.new NewVideoTask(name, id, type));
            } catch (JSONException | UnsupportedEncodingException e) {
                Log.w(TAG, e);
            }
        }
    }
}

From source file:com.facebook.internal.BundleJSONConverterTest.java

@Test
public void testSimpleValues() throws JSONException {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1st");
    arrayList.add("2nd");
    arrayList.add("third");

    Bundle innerBundle1 = new Bundle();
    innerBundle1.putInt("inner", 1);

    Bundle innerBundle2 = new Bundle();
    innerBundle2.putString("inner", "2");
    innerBundle2.putStringArray("deep list", new String[] { "7", "8" });

    innerBundle1.putBundle("nested bundle", innerBundle2);

    Bundle b = new Bundle();
    b.putBoolean("boolValue", true);
    b.putInt("intValue", 7);
    b.putLong("longValue", 5000000000l);
    b.putDouble("doubleValue", 3.14);
    b.putString("stringValue", "hello world");
    b.putStringArray("stringArrayValue", new String[] { "first", "second" });
    b.putStringArrayList("stringArrayListValue", arrayList);
    b.putBundle("nested", innerBundle1);

    JSONObject json = BundleJSONConverter.convertToJSON(b);
    assertNotNull(json);/*from w ww. j  a  v  a 2s.  c o m*/

    assertEquals(true, json.getBoolean("boolValue"));
    assertEquals(7, json.getInt("intValue"));
    assertEquals(5000000000l, json.getLong("longValue"));
    assertEquals(3.14, json.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA);
    assertEquals("hello world", json.getString("stringValue"));

    JSONArray jsonArray = json.getJSONArray("stringArrayValue");
    assertEquals(2, jsonArray.length());
    assertEquals("first", jsonArray.getString(0));
    assertEquals("second", jsonArray.getString(1));

    jsonArray = json.getJSONArray("stringArrayListValue");
    assertEquals(3, jsonArray.length());
    assertEquals("1st", jsonArray.getString(0));
    assertEquals("2nd", jsonArray.getString(1));
    assertEquals("third", jsonArray.getString(2));

    JSONObject innerJson = json.getJSONObject("nested");
    assertEquals(1, innerJson.getInt("inner"));
    innerJson = innerJson.getJSONObject("nested bundle");
    assertEquals("2", innerJson.getString("inner"));

    jsonArray = innerJson.getJSONArray("deep list");
    assertEquals(2, jsonArray.length());
    assertEquals("7", jsonArray.getString(0));
    assertEquals("8", jsonArray.getString(1));

    Bundle finalBundle = BundleJSONConverter.convertToBundle(json);
    assertNotNull(finalBundle);

    assertEquals(true, finalBundle.getBoolean("boolValue"));
    assertEquals(7, finalBundle.getInt("intValue"));
    assertEquals(5000000000l, finalBundle.getLong("longValue"));
    assertEquals(3.14, finalBundle.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA);
    assertEquals("hello world", finalBundle.getString("stringValue"));

    List<String> stringList = finalBundle.getStringArrayList("stringArrayValue");
    assertEquals(2, stringList.size());
    assertEquals("first", stringList.get(0));
    assertEquals("second", stringList.get(1));

    stringList = finalBundle.getStringArrayList("stringArrayListValue");
    assertEquals(3, stringList.size());
    assertEquals("1st", stringList.get(0));
    assertEquals("2nd", stringList.get(1));
    assertEquals("third", stringList.get(2));

    Bundle finalInnerBundle = finalBundle.getBundle("nested");
    assertEquals(1, finalInnerBundle.getInt("inner"));
    finalBundle = finalInnerBundle.getBundle("nested bundle");
    assertEquals("2", finalBundle.getString("inner"));

    stringList = finalBundle.getStringArrayList("deep list");
    assertEquals(2, stringList.size());
    assertEquals("7", stringList.get(0));
    assertEquals("8", stringList.get(1));
}

From source file:org.protorabbit.Config.java

static void processURIResources(int type, JSONObject bsjo, ITemplate temp, String baseURI)
        throws JSONException {

    List<ResourceURI> refs = null;
    refs = new ArrayList<ResourceURI>();

    if (bsjo.has("libs")) {

        JSONArray ja = bsjo.getJSONArray("libs");

        for (int j = 0; j < ja.length(); j++) {

            JSONObject so = ja.getJSONObject(j);
            String url = so.getString("url");
            if (url.startsWith("/") || url.startsWith("http")) {
                baseURI = "";
            }//from   w w w.j a v a 2 s .c  om
            ResourceURI ri = new ResourceURI(url, baseURI, type);
            if (so.has("id")) {
                ri.setId(so.getString("id"));
            }
            if (so.has("uaTest")) {
                ri.setUATest(so.getString("uaTest"));
            }
            if (so.has("test")) {
                ri.setTest(so.getString("test"));
            }
            if (so.has("defer")) {
                ri.setDefer(so.getBoolean("defer"));
            }
            if (so.has("combine")) {
                ri.setCombine(so.getBoolean("combine"));
            }
            if (so.has("uniqueURL")) {
                Boolean unique = so.getBoolean("uniqueURL");
                ri.setUniqueURL(unique);
            }
            refs.add(ri);
        }
    }
    Boolean combine = null;
    if (bsjo.has("combineResources")) {
        combine = bsjo.getBoolean("combineResources");
    }
    Boolean lgzip = null;
    if (bsjo.has("gzip")) {
        lgzip = bsjo.getBoolean("gzip");
    }

    if (type == ResourceURI.SCRIPT) {
        temp.setCombineScripts(combine);
        temp.setGzipScripts(lgzip);
        temp.setScripts(refs);
    } else if (type == ResourceURI.LINK) {
        temp.setGzipStyles(lgzip);
        temp.setStyles(refs);
        temp.setCombineStyles(combine);
    }
}

From source file:org.protorabbit.Config.java

@SuppressWarnings("unchecked")
private void registerTemplates(ITemplate temp, JSONObject t, String baseURI) {

    try {/*from   w w w . ja  v  a  2 s .co  m*/

        if (t.has("timeout")) {
            long templateTimeout = t.getLong("timeout");
            temp.setTimeout(templateTimeout);
        }

        boolean tgzip = false;

        if (!devMode) {
            tgzip = gzip;
        }

        if (t.has("gzip")) {
            tgzip = t.getBoolean("gzip");
            temp.setGzipStyles(tgzip);
            temp.setGzipScripts(tgzip);
            temp.setGzipTemplate(tgzip);
        }

        if (t.has("uniqueURL")) {
            Boolean unique = t.getBoolean("uniqueURL");
            temp.setUniqueURL(unique);
        }

        // template overrides default combineResources
        if (t.has("combineResources")) {
            boolean combineResources = t.getBoolean("combineResources");
            temp.setCombineResources(combineResources);
            temp.setCombineScripts(combineResources);
            temp.setCombineStyles(combineResources);
        }

        if (t.has("template")) {
            String turi = t.getString("template");
            ResourceURI templateURI = new ResourceURI(turi, baseURI, ResourceURI.TEMPLATE);
            temp.setTemplateURI(templateURI);
        }

        if (t.has("namespace")) {
            temp.setURINamespace(t.getString("namespace"));
        }

        if (t.has("extends")) {
            List<String> ancestors = null;
            String base = t.getString("extends");
            if (base.length() > 0) {
                String[] parentIds = null;
                if (base.indexOf(",") != -1) {
                    parentIds = base.split(",");
                } else {
                    parentIds = new String[1];
                    parentIds[0] = base;
                }
                ancestors = new ArrayList<String>();

                for (int j = 0; j < parentIds.length; j++) {
                    ancestors.add(parentIds[j].trim());
                }
            }

            temp.setAncestors(ancestors);
        }

        if (t.has("overrides")) {

            List<TemplateOverride> overrides = new ArrayList<TemplateOverride>();
            JSONArray joa = t.getJSONArray("overrides");
            for (int z = 0; z < joa.length(); z++) {
                TemplateOverride tor = new TemplateOverride();
                JSONObject toro = joa.getJSONObject(z);
                if (toro.has("test")) {
                    tor.setTest(toro.getString("test"));
                }
                if (toro.has("uaTest")) {
                    tor.setUATest(toro.getString("uaTest"));
                }
                if (toro.has("import")) {
                    tor.setImportURI(toro.getString("import"));
                }
                overrides.add(tor);
            }
            temp.setTemplateOverrides(overrides);
        }

        if (t.has("scripts")) {

            JSONObject bsjo = t.getJSONObject("scripts");

            processURIResources(ResourceURI.SCRIPT, bsjo, temp, baseURI);
        }

        if (t.has("styles")) {
            JSONObject bsjo = t.getJSONObject("styles");

            processURIResources(ResourceURI.LINK, bsjo, temp, baseURI);
        }

        if (t.has("properties")) {

            Map<String, IProperty> properties = null;
            JSONObject po = t.getJSONObject("properties");
            properties = new HashMap<String, IProperty>();

            Iterator<String> jit = po.keys();
            while (jit.hasNext()) {

                String name = jit.next();
                JSONObject so = po.getJSONObject(name);
                int type = IProperty.STRING;
                String value = so.getString("value");

                if (so.has("type")) {

                    String typeString = so.getString("type");

                    if ("string".equals(typeString.toLowerCase())) {
                        type = IProperty.STRING;
                    } else if ("include".equals(typeString.toLowerCase())) {
                        type = IProperty.INCLUDE;
                    }
                }

                IProperty pi = new Property(name, value, type, baseURI, temp.getId());

                if (so.has("timeout")) {
                    long timeout = so.getLong("timeout");
                    pi.setTimeout(timeout);
                }
                if (so.has("id")) {
                    pi.setId(so.getString("id"));
                }
                if (so.has("uaTest")) {
                    pi.setUATest(so.getString("uaTest"));
                }
                if (so.has("test")) {
                    pi.setTest(so.getString("test"));
                }
                if (so.has("defer")) {
                    pi.setDefer(so.getBoolean("defer"));
                }
                if (so.has("deferContent")) {
                    pi.setDeferContent(new StringBuffer(so.getString("deferContent")));
                }
                properties.put(name, pi);
            }
            temp.setProperties(properties);
        }

    } catch (JSONException e) {
        getLogger().log(Level.SEVERE, "Error parsing configuration.", e);
    }

}

From source file:ub.botiga.data.User.java

public User(JSONObject obj, HashMap<String, Product> totalproducts) throws JSONException {
    this.mName = obj.getString("name");
    this.mCredit = (float) obj.getDouble("credit");
    this.mProducts = new HashMap<String, Product>();
    JSONArray m = obj.getJSONArray("products");
    String p;//from  ww  w .jav  a  2  s  .c o  m
    for (int i = 0; i < m.length(); i++) {
        p = m.getString(i);
        if (totalproducts.containsKey(p)) {
            mProducts.put(p, totalproducts.get(p));
        }
    }

}