Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:com.orange.mmp.api.ws.jsonrpc.SimpleJSONSerializer.java

/**
 * Replace getClassFromHint from super class to avoid using class hint
 * @param o a JSONObject or JSONArray object to get the Class type
 * @return the Class found, or null if the passed in Object is null
 *
 * @throws UnmarshallException if javaClass was not found
 *///from   w  w  w . j a v a2s. c o m
@SuppressWarnings("unchecked")
private Class getClass(Object o) throws UnmarshallException {
    if (o == null) {
        return null;
    }

    if (o instanceof JSONArray) {
        JSONArray arr = (JSONArray) o;
        if (arr.length() == 0) {
            //             throw new UnmarshallException("no type for empty array");
            try {
                return Class.forName("[L" + Integer.class.getName() + ";");
            } catch (ClassNotFoundException e) {
                // XXX Warning: if this block doesn't fit, just throw the following exception
                // This block is used by SynchronizeAPI, when an empty blocks list is provided 
                throw new UnmarshallException("no type for empty array");
            }
        }

        Class compClazz;
        try {
            compClazz = getClass(arr.get(0));
            int arrayLgth = arr.length();
            for (int index = 0; index < arrayLgth; index++) {
                if (!getClass(arr.get(index)).isAssignableFrom(compClazz)) {
                    return java.util.List.class;
                }
            }
        } catch (JSONException e) {
            throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e);
        }

        try {
            if (compClazz.isArray()) {
                return Class.forName("[" + compClazz.getName());
            }
            return Class.forName("[L" + compClazz.getName() + ";");
        } catch (ClassNotFoundException e) {
            throw new UnmarshallException("problem getting array type");
        }
    }
    return o.getClass();
}

From source file:com.aokp.romcontrol.github.tasks.GetJSONChangelogTask.java

protected Void doInBackground(Void... unused) {
    HttpClient httpClient = null;//from  ww  w.  j  ava  2s  .  c  o  m
    try {
        httpClient = new DefaultHttpClient();
        String url = String.valueOf(STATIC_DEBUG ? "https://raw.github.com/JBirdVegas/tests/master/example.json"
                : mConfig.CHANGELOG_JSON);
        HttpGet requestWebsite = new HttpGet(url);
        Log.d(TAG, "attempting to connect to: " + url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());
        if (Config.StaticVars.JSON_SPEW)
            Log.d(TAG, "projectCommitsArray.toString() is: " + projectCommitsArray.toString());

        final ChangelogObject commitObject = new ChangelogObject(new JSONObject());
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            JSONObject projectsObject = (JSONObject) projectCommitsArray.get(i);
            PreferenceScreen newCommitPreference = mCategory.getPreferenceManager()
                    .createPreferenceScreen(mContext);
            commitObject.reParse(projectsObject);
            newCommitPreference.setTitle(commitObject.getSubject());
            newCommitPreference.setSummary(commitObject.getBody());
            newCommitPreference.setKey(commitObject.getCommitHash());
            newCommitPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    mAlertDialog.setCommitAndShow(commitObject);
                    return false;
                }
            });
            mCategory.addPreference(newCommitPreference);
        }
    } catch (HttpResponseException httpError) {
        Log.e(TAG, "bad HTTP response:", httpError);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "client protocal exception:", e);
    } catch (JSONException e) {
        Log.d(TAG, "bad json interaction:", e);
    } catch (IOException e) {
        Log.d(TAG, "io exception:", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return null;
}

From source file:run.ace.IncomingMessages.java

public static void set(JSONArray message) throws JSONException {
    Object instance = Handle.deserialize(message.getJSONObject(1));
    String propertyName = message.getString(2);
    Object propertyValue = message.get(3);

    // Convert non-primitives (TODO arrays)
    if (propertyValue instanceof JSONObject) {
        propertyValue = Utils.deserializeObjectOrStruct((JSONObject) propertyValue);
    } else if (propertyValue == JSONObject.NULL) {
        propertyValue = null;//from   w  w  w. j  ava 2s  .  c o m
    }

    try {
        if (instance instanceof IHaveProperties) {
            ((IHaveProperties) instance).setProperty(propertyName, propertyValue);
        } else {
            // Try reflection. So XXX.YYY maps to a setYYY method.
            try {
                String setterName = "set";
                if (propertyName.contains(".")) {
                    setterName += propertyName.substring(propertyName.lastIndexOf(".") + 1);
                } else {
                    setterName += propertyName;
                }

                //TODO: Need to do more permissive parameter matching in this case since everything will be strings.
                // Started to add this with looseMatching param. Continue.
                try {
                    Integer value = Integer.parseInt(propertyValue.toString());
                    propertyValue = value;
                } catch (java.lang.NumberFormatException nfe) {
                    try {
                        Double value = Double.parseDouble(propertyValue.toString());
                        propertyValue = value;
                    } catch (java.lang.NumberFormatException nfe2) {
                        // Keep as string
                    }
                }

                // TODO: Enable marshaling of things like "red" to Drawable...

                Utils.invokeMethodWithBestParameterMatch(instance.getClass(), setterName, instance,
                        new Object[] { propertyValue }, true);
            } catch (Exception ex) {
                //
                // Translate standard cross-platform (XAML) properties for well-known base types
                //
                if (instance instanceof TextView) {

                    if (propertyName.endsWith(".Children") && propertyValue instanceof ItemCollection) {
                        // This is from XAML compilation of a custom content property, which always gives an ItemCollection.
                        propertyName = "ContentControl.Content";
                        if (((ItemCollection) propertyValue).size() == 1) {
                            propertyValue = ((ItemCollection) propertyValue).get(0);
                        }
                    }

                    if (!TextViewHelper.setProperty((TextView) instance, propertyName, propertyValue)) {
                        throw new RuntimeException("Unhandled property for a custom TextView: " + propertyName
                                + ". Implement IHaveProperties to support this.");
                    }
                } else if (instance instanceof ViewGroup) {
                    if (propertyName.endsWith(".Children") && propertyValue instanceof ItemCollection) {
                        // This is from XAML compilation of a custom content property, which always gives an ItemCollection.
                        ItemCollection children = (ItemCollection) propertyValue;
                        for (int i = 0; i < children.size(); i++) {
                            ((ViewGroup) instance).addView((View) children.get(i));
                        }
                    } else if (!ViewGroupHelper.setProperty((ViewGroup) instance, propertyName,
                            propertyValue)) {
                        throw new RuntimeException("Unhandled property for a custom ViewGroup: " + propertyName
                                + ". Implement IHaveProperties to support this.");
                    }
                } else if (instance instanceof View) {
                    if (!ViewHelper.setProperty((View) instance, propertyName, propertyValue, true)) {
                        throw new RuntimeException("Unhandled property for a custom View: " + propertyName
                                + ". Implement IHaveProperties to support this.");
                    }
                } else {
                    throw new RuntimeException("Either there must be a set" + propertyName
                            + " method, or IHaveProperties must be implemented.");
                }
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Error setting " + instance.getClass().getSimpleName() + "'s " + propertyName
                + " to " + propertyValue, ex);
    }
}

From source file:run.ace.IncomingMessages.java

public static void fieldSet(JSONArray message) throws JSONException {
    Object instance = Handle.deserialize(message.getJSONObject(1));
    String fieldName = message.getString(2);
    Object fieldValue = message.get(3);

    // Convert non-primitives
    if (fieldValue instanceof JSONObject) {
        fieldValue = Utils.deserializeObjectOrStruct((JSONObject) fieldValue);
    } else if (fieldValue == JSONObject.NULL) {
        fieldValue = null;// w  w  w .  j ava2 s  .  c om
    }

    Utils.setField(instance.getClass(), instance, fieldName, fieldValue);
}

From source file:cc.redpen.server.api.RedPenResourceTest.java

public void testRunWithErrors() throws Exception {
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD);
    request.setContent(("document=foobar.foobar").getBytes()); //NOTE: need space between periods.
    MockHttpServletResponse response = invoke(request);

    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
    System.out.println(response.getContentAsString());
    JSONArray errors = (JSONArray) new JSONObject(response.getContentAsString()).get("errors");
    // the following will change whenever the configuration or validator functionaliy changes
    // but it doesn't indicate what particular errors are new/missing
    // assertEquals(3, errors.length());
    assertTrue(errors.get(0).toString().length() > 0);
}

From source file:com.handshake.notifications.MyGcmListenerService.java

/**
 * Called when message is received./*w ww.j av a2  s.co  m*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, final Bundle data) {
    SessionManager session = new SessionManager(this);
    if (!session.isLoggedIn())
        return;

    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */

    try {
        final JSONArray users = new JSONArray();
        if (!data.containsKey("user"))
            return;
        final JSONObject user = new JSONObject(data.getString("user"));
        users.put(user);
        UserServerSync.cacheUser(getApplicationContext(), users, new UserArraySyncCompleted() {
            @Override
            public void syncCompletedListener(final ArrayList<User> users) {
                if (users.size() == 0) {
                    sendNotification(data, 0, false);
                    return;
                }

                final long userId = users.get(0).getUserId();
                final boolean isContact = users.get(0).isContact();

                FeedItemServerSync.performSync(getApplicationContext(), new SyncCompleted() {
                    @Override
                    public void syncCompletedListener() {
                        ContactSync.performSync(getApplicationContext(), new SyncCompleted() {
                            @Override
                            public void syncCompletedListener() {
                                if (data.containsKey("group_id")) {
                                    Realm realm = Realm.getInstance(getApplicationContext());
                                    Group group = realm.where(Group.class)
                                            .equalTo("groupId", Long.parseLong(data.getString("group_id")))
                                            .findFirst();
                                    GroupServerSync.loadGroupMembers(group);
                                    realm.close();
                                }

                                sendNotification(data, userId, isContact);
                            }
                        });
                    }
                });
            }
        });
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.uiautomation.ios.server.command.web.SetValueHandler.java

@Override
public Response handle() throws Exception {
    int id = Integer.parseInt(getRequest().getVariableValue(":reference"));
    RemoteWebElement element = new RemoteWebElement(new NodeId(id), getSession());

    JSONArray array = getRequest().getPayload().getJSONArray("value");
    String value = "";
    if (array.length() == 1) {
        Object o = array.get(0);
        if (o instanceof String) {
            value = (String) o;/*  www . jav a 2  s .c  om*/
        } else {
            throw new RuntimeException("NI");
        }
    } else {
        throw new RuntimeException("NI");
    }

    boolean useNativeEvents = getConfiguration("nativeEvents", nativeEvents);

    if (useNativeEvents) {
        element.setValueNative(value);
    } else {
        element.setValueAtoms(value);
    }

    Response res = new Response();
    res.setSessionId(getSession().getSessionId());
    res.setStatus(0);
    res.setValue(new JSONObject());
    return res;
}

From source file:uk.thetasinner.concordion.extension.json.internal.JsonComparer.java

private void compareJsonArrays(JSONArray expected, JSONArray actual, String keyPath) {
    int expectedLength = expected.length();
    int actualLength = actual.length();

    checkArrayLengthsMatch(expectedLength, actualLength, keyPath);

    int maxArrayLength = Math.max(expectedLength, actualLength);
    for (int i = 0; i < maxArrayLength; i++) {
        if (i >= expectedLength) {
            jsonDiffLines.add("Extra array element <" + actual.get(i) + ">" + JsonKeyPath.format(keyPath));
            continue;
        }//w ww  . jav  a  2  s .  com

        if (i >= actualLength) {
            jsonDiffLines.add("Missing array element <" + expected.get(i) + ">" + JsonKeyPath.format(keyPath));
            continue;
        }

        routeComparison(expected, actual, keyPath, i);
    }
}

From source file:uk.thetasinner.concordion.extension.json.internal.JsonComparer.java

private void routeComparison(JSONArray expected, JSONArray actual, String keyPath, int index) {
    Object expectedValue = expected.get(index);
    Object actualValue = actual.get(index);

    routeComparison(expectedValue, actualValue, JsonKeyPath.navigateTo(keyPath, index));
}

From source file:org.zaizi.sensefy.api.utils.JSONHelper.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList(JSONArray array) throws JSONException {
    List list = new ArrayList();
    for (int i = 0; i < array.length(); i++) {
        list.add(fromJson(array.get(i)));
    }/*from ww w  .  ja  va 2 s. c  o m*/
    return list;
}