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:ai.susi.mind.SusiThought.java

/**
 * create a clone of a json object as a SusiThought object
 * @param json the 'other' thought, probably an exported and re-imported thought
 *///from ww w .j  a v a  2  s . co m
public SusiThought(JSONObject json) {
    this();
    if (json.has(this.metadata_name))
        this.put(this.metadata_name, json.getJSONObject(this.metadata_name));
    if (json.has(this.data_name))
        this.setData(json.getJSONArray(this.data_name));
    if (json.has("actions"))
        this.put("actions", json.getJSONArray("actions"));
}

From source file:com.krayzk9s.imgurholo.ui.AccountFragment.java

public void onGetObject(Object data, String tag) {
    refreshedCount++;// w w  w . j a va 2  s.  c  o  m
    if (refreshedCount == 5) {
        mPullToRefreshLayout.setRefreshComplete();
    }
    try {
        if (data == null) {
            return;
        }
        JSONObject jsonData;

        /*int duration = Toast.LENGTH_SHORT;
            Toast toast;
        MainActivity activity = (MainActivity) getActivity();
        toast = Toast.makeText(activity, "User not found", duration);
        toast.show();
        activity.getFragmentManager().popBackStack();*/

        if (tag.equals(ACCOUNTDATA)) {
            jsonData = ((JSONObject) data).getJSONObject("data");
            if (jsonData.has("error"))
                return;
            Calendar accountCreationDate = Calendar.getInstance();
            accountCreationDate.setTimeInMillis((long) jsonData.getInt("created") * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            String accountcreated = sdf.format(accountCreationDate.getTime());
            created.setText(accountcreated);
            reputation.setText(Integer.toString(jsonData.getInt("reputation")));
            if (jsonData.getString("bio") != null && !jsonData.getString("bio").equals("null")
                    && !jsonData.getString("bio").equals(""))
                biography.setText(jsonData.getString("bio"));
            else
                biography.setText("No Biography");
        } else if (tag.equals(COUNTDATA)) {
            jsonData = ((JSONObject) data);
            if (jsonData.has("error"))
                return;
            if (jsonData.getInt("status") == 200)
                mMenuList[1] = mMenuList[1] + " (" + Integer.toString(jsonData.getInt("data")) + ")";
            else
                mMenuList[1] = mMenuList[1] + " (0)";
        } else if (tag.equals(ALBUMDATA)) {
            jsonData = ((JSONObject) data);
            if (jsonData.has("error"))
                return;
            if (jsonData.getInt("status") == 200)
                mMenuList[0] = mMenuList[0] + " (" + Integer.toString(jsonData.getJSONArray("data").length())
                        + ")";
            else
                mMenuList[0] = mMenuList[0] + " (0)";
        } else if (tag.equals(LIKEDATA)) {
            JSONArray jsonArray = ((JSONObject) data).getJSONArray("data");
            mMenuList[2] = mMenuList[2] + " (" + String.valueOf(jsonArray.length()) + ")";
        } else if (tag.equals(COMMENTDATA)) {
            jsonData = ((JSONObject) data);
            mMenuList[3] = mMenuList[3] + " (" + String.valueOf(jsonData.getInt("data")) + ")";
        }
        adapter.notifyDataSetChanged();
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
}

From source file:vOS.controller.socket.IOConnection.java

/**
 * Transport message. {@link IOTransport} calls this, when a message has
 * been received./*from  w w w.  j  a  v  a2  s . co  m*/
 * 
 * @param text
 *            the text
 */
public void transportMessage(String text) {
    logger.info("< " + text);
    IOMessage message;
    try {
        message = new IOMessage(text);
    } catch (Exception e) {
        error(new SocketIOException("Garbage from server: " + text, e));
        return;
    }
    resetTimeout();
    switch (message.getType()) {
    case IOMessage.TYPE_DISCONNECT:
        try {
            findCallback(message).onDisconnect();
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onDisconnect()", e));
        }
        break;
    case IOMessage.TYPE_CONNECT:
        try {
            if (firstSocket != null && "".equals(message.getEndpoint())) {
                if (firstSocket.getNamespace().equals("")) {
                    firstSocket.getCallback().onConnect();
                } else {
                    IOMessage connect = new IOMessage(IOMessage.TYPE_CONNECT, firstSocket.getNamespace(), "");
                    sendPlain(connect.toString());
                }
            } else {
                findCallback(message).onConnect();
            }
            firstSocket = null;
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onConnect()", e));
        }
        break;
    case IOMessage.TYPE_HEARTBEAT:
        sendPlain("2::");
        break;
    case IOMessage.TYPE_MESSAGE:
        try {
            findCallback(message).onMessage(message.getData(), remoteAcknowledge(message));
        } catch (Exception e) {
            error(new SocketIOException(
                    "Exception was thrown in onMessage(String).\n" + "Message was: " + message.toString(), e));
        }
        break;
    case IOMessage.TYPE_JSON_MESSAGE:
        try {
            JSONObject obj = null;
            String data = message.getData();
            if (data.trim().equals("null") == false)
                obj = new JSONObject(data);
            try {
                findCallback(message).onMessage(obj, remoteAcknowledge(message));
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in onMessage(JSONObject).\n" + "Message was: "
                        + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;
    case IOMessage.TYPE_EVENT:
        try {
            JSONObject event = new JSONObject(message.getData());
            Object[] argsArray;
            if (event.has("args")) {
                JSONArray args = event.getJSONArray("args");
                argsArray = new Object[args.length()];
                for (int i = 0; i < args.length(); i++) {
                    if (args.isNull(i) == false)
                        argsArray[i] = args.get(i);
                }
            } else
                argsArray = new Object[0];
            String eventName = event.getString("name");
            try {
                findCallback(message).on(eventName, remoteAcknowledge(message), argsArray);
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in on(String, JSONObject[]).\n"
                        + "Message was: " + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;

    case IOMessage.TYPE_ACK:
        String[] data = message.getData().split("\\+", 2);
        if (data.length == 2) {
            try {
                int id = Integer.parseInt(data[0]);
                IOAcknowledge ack = acknowledge.get(id);
                if (ack == null)
                    logger.warning("Received unknown ack packet");
                else {
                    JSONArray array = new JSONArray(data[1]);
                    Object[] args = new Object[array.length()];
                    for (int i = 0; i < args.length; i++) {
                        args[i] = array.get(i);
                    }
                    ack.ack(args);
                }
            } catch (NumberFormatException e) {
                logger.warning(
                        "Received malformated Acknowledge! This is potentially filling up the acknowledges!");
            } catch (JSONException e) {
                logger.warning("Received malformated Acknowledge data!");
            }
        } else if (data.length == 1) {
            sendPlain("6:::" + data[0]);
        }
        break;
    case IOMessage.TYPE_ERROR:
        try {
            findCallback(message).onError(new SocketIOException(message.getData()));
        } catch (SocketIOException e) {
            error(e);
        }
        if (message.getData().endsWith("+0")) {
            // We are advised to disconnect
            cleanup();
        }
        break;
    case IOMessage.TYPE_NOOP:
        break;
    default:
        logger.warning("Unkown type received" + message.getType());
        break;
    }
}

From source file:com.imaginary.home.cloud.device.Light.java

static void mapLight(@Nonnull ControllerRelay relay, @Nonnull JSONObject json,
        @Nonnull Map<String, Object> state) throws JSONException {
    mapPoweredDevice(relay, json, state);
    state.put("deviceType", "light");
    if (json.has("color")) {
        JSONObject color = json.getJSONObject("color");
        ColorMode colorMode = null;/* w  ww.  ja v a2  s .  co m*/
        float[] components = null;

        if (color.has("colorMode") && !color.isNull("colorMode")) {
            try {
                colorMode = ColorMode.valueOf(color.getString("colorMode"));
            } catch (IllegalArgumentException e) {
                throw new JSONException("Invalid color mode: " + color.getString("colorMode"));
            }
        }
        if (color.has("components") && !color.isNull("components")) {
            JSONArray arr = color.getJSONArray("components");
            components = new float[arr.length()];

            for (int i = 0; i < arr.length(); i++) {
                components[i] = (float) arr.getDouble(i);
            }
        }
        if (colorMode != null || components != null) {
            state.put("colorMode", colorMode);
            state.put("colorValues", components);
        }
    }
    if (json.has("brightness") && !json.isNull("brightness")) {
        state.put("brightness", (float) json.getDouble("brightness"));
    }
    if (json.has("supportsColorChanges")) {
        state.put("colorChangeSupported",
                !json.isNull("supportsColorChanges") && json.getBoolean("supportsColorChanges"));
    }
    if (json.has("supportsBrightnessChanges")) {
        state.put("dimmable",
                !json.isNull("supportsBrightnessChanges") && json.getBoolean("supportsBrightnessChanges"));
    }
    if (json.has("colorModes")) {
        JSONArray arr = json.getJSONArray("colorModes");
        ColorMode[] modes = new ColorMode[arr.length()];

        for (int i = 0; i < arr.length(); i++) {
            try {
                modes[i] = ColorMode.valueOf(arr.getString(i));
            } catch (IllegalArgumentException e) {
                throw new JSONException("Invalid color mode: " + arr.getString(i));
            }
        }
        state.put("colorModesSupported", modes);
    }
}

From source file:com.norman0406.slimgress.API.Plext.PlextBase.java

protected PlextBase(PlextType type, JSONArray json) throws JSONException {
    super(json);//from  www. j a va  2  s  .  c o m
    mPlextType = type;

    JSONObject item = json.getJSONObject(2);

    JSONObject plext = item.getJSONObject("plext");
    JSONArray markup = plext.getJSONArray("markup");

    mText = plext.getString("text");

    mMarkups = new LinkedList<Markup>();
    for (int i = 0; i < markup.length(); i++) {
        JSONArray markupItem = markup.getJSONArray(i);

        Markup newMarkup = Markup.createByJSON(markupItem);
        if (newMarkup != null)
            mMarkups.add(newMarkup);
    }
}

From source file:org.dspace.globus.Globus.java

public static String getAllMetadata(Context context, Item item, Collection collection) {
    try {/*from   w  w  w. java2s  . c om*/
        JSONObject dataset = new JSONObject();
        if (collection == null) {
            collection = item.getOwningCollection();
        }
        Community community = collection.getCommunities()[0];
        EPerson person = item.getSubmitter();

        dataset.put("_comment", "This file was auto-generated by Globus");
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "submitter"), person.getGlobusUserName());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "collection"), collection.getName());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "collection_id"), collection.getID());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "community"), community.getName());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "community_id"), community.getID());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "item_id"), item.getID());

        Set<String> schemas = new HashSet<String>();
        schemas.add("globus");
        String key;
        DCValue[] dcv = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
        for (DCValue dcval : dcv) {
            // Make a unique key for this piece of metadata
            // if its a DC term we map to datacite
            if (dublinCoreDataciteMap.containsKey(dcval.getField())) {
                key = dublinCoreDataciteMap.getProperty(dcval.getField());
                schemas.add("datacite");
            } else {
                key = Globus.makeJSONLDKey(dcval);
                schemas.add(dcval.schema);
            }
            // We assume all metadata values could be multivalued
            // There is no way to tell so we encode all in an array
            JSONArray valueArray = null;
            if (!dataset.has(key)) {
                valueArray = new JSONArray();
            } else {
                valueArray = dataset.getJSONArray(key);
            }
            valueArray.put(dcval.value);
            dataset.put(key, valueArray);
        }
        // create JSON-LD context heading
        JSONObject jsonLDContext = new JSONObject();
        MetadataSchema metadataSchema;
        for (String s : schemas) {
            metadataSchema = MetadataSchema.find(context, s);
            jsonLDContext.put(s, metadataSchema.getNamespace());
        }
        dataset.put("@context", jsonLDContext);
        return dataset.toString();
    } catch (Exception e) {
        logger.error("Error getting item metadata " + e);
    }
    return "";
}

From source file:com.richtodd.android.quiltdesign.block.Quilt.java

static final Quilt createFromJSONObject(JSONObject jsonObject) throws JSONException {

    int rowCount = jsonObject.optInt("rowCount", 0);
    int columnCount = jsonObject.optInt("columnCount", 0);
    float width = (float) jsonObject.optDouble("width", 0);
    float height = (float) jsonObject.optDouble("height", 0);

    Quilt quilt = new Quilt(rowCount, columnCount, width, height);

    if (jsonObject.has("quiltBlocks")) {
        JSONArray jsonQuiltBlocks = jsonObject.getJSONArray("quiltBlocks");

        int index = -1;
        for (int row = 0; row < quilt.m_rowCount; ++row) {
            for (int column = 0; column < quilt.m_columnCount; ++column) {
                index += 1;/*from   www  .java  2  s  .c  o m*/
                if (index < jsonQuiltBlocks.length()) {
                    JSONObject jsonQuiltBlock = jsonQuiltBlocks.optJSONObject(index);
                    if (jsonQuiltBlock != null) {
                        QuiltBlock quiltBlock = QuiltBlock.createFromJSONObject(jsonQuiltBlock);
                        quilt.setQuiltBlock(row, column, quiltBlock);
                    }
                }
            }
        }
    }

    quilt.m_new = false;
    return quilt;
}

From source file:com.leanengine.JsonDecode.java

static LeanEntity[] entityListFromJson(JSONObject json) throws LeanException {
    try {//from w  w  w.  j av a2s. c  o m
        JSONArray array = json.getJSONArray("result");
        LeanEntity[] result = new LeanEntity[array.length()];
        for (int i = 0; i < array.length(); i++) {
            JSONObject item = array.getJSONObject(i);
            result[i] = entityFromJson(item);
        }
        return result;
    } catch (JSONException e) {
        throw new LeanException(LeanError.Type.ServerError, "Malformed reply: " + e);
    }
}

From source file:com.fatsecret.platform.utils.FoodUtility.java

/**
 * Returns detailed information about the food
 * /*  www .  j  a  va2s.  c o m*/
 * @param json         json object representing of the food
 * @return            detailed information about the food
 */
public static Food parseFoodFromJSONObject(JSONObject json) {
    String name = json.getString("food_name");
    String url = json.getString("food_url");
    String type = json.getString("food_type");
    Long id = Long.parseLong(json.getString("food_id"));
    String brandName = "";

    try {
        brandName = json.getString("brand_name");
    } catch (Exception ignore) {
    }

    JSONObject servingsObj = json.getJSONObject("servings");

    JSONArray array = null;
    List<Serving> servings = new ArrayList<Serving>();

    try {
        array = servingsObj.getJSONArray("serving");
        servings = ServingUtility.parseServingsFromJSONArray(array);
    } catch (Exception ignore) {
        System.out.println("Servings not found");
        array = null;
    }

    if (array == null) {
        try {
            JSONObject servingObj = servingsObj.getJSONObject("serving");
            Serving serving = ServingUtility.parseServingFromJSONObject(servingObj);
            servings.add(serving);
        } catch (Exception ignore) {
            System.out.println("Serving not found");
        }
    }

    Food food = new Food();

    food.setName(name);
    food.setUrl(url);
    food.setType(type);
    food.setId(id);
    food.setBrandName(brandName);
    food.setServings(servings);

    return food;
}

From source file:com.microsoft.services.sharepoint.OfficeEntity.java

/**
 * List from json./*from w  w  w .  j  a v a  2  s.  c  o m*/
 * 
 * @param <E>
 *            the element type
 * @param json
 *            the json
 * @param clazz
 *            the clazz
 * @return the list
 * @throws org.json.JSONException
 *             the JSON exception
 */
protected static <E extends OfficeEntity> List<E> listFromJson(JSONObject json, Class<E> clazz)
        throws JSONException {
    List<E> list = new ArrayList<E>();

    JSONArray results;
    if (json.has("d")) {
        results = json.getJSONObject("d").getJSONArray("results");
    } else {
        results = json.getJSONArray("results");
    }

    for (int i = 0; i < results.length(); i++) {
        JSONObject result = results.getJSONObject(i);

        E item = null;
        try {
            item = clazz.newInstance();
        } catch (Throwable e) {
        }

        if (item != null) {
            item.loadFromJson(result);
            list.add(item);
        }
    }

    return list;
}