Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

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

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

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

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

    final JSONObject jso = (JSONObject) o;
    BeanData bd;/*from  ww w .  ja  v  a2  s. c o  m*/
    try {
        bd = getBeanData(clazz);
    } catch (final IntrospectionException e) {
        throw new UnmarshallException(clazz.getName() + " is not a bean", e);
    }

    int match = 0;
    int mismatch = 0;
    for (final String prop : bd.writableProps.keySet()) {
        if (jso.has(prop)) {
            match++;
        } else {
            mismatch++;
        }
    }
    if (match == 0) {
        throw new UnmarshallException("bean has no matches");
    }

    // create a concrete ObjectMatch that is always returned in order to
    // satisfy circular reference requirements
    final ObjectMatch returnValue = new ObjectMatch(-1);
    state.setSerialized(o, returnValue);

    ObjectMatch m = null;
    ObjectMatch tmp;
    final Iterator<?> i = jso.keys();
    while (i.hasNext()) {
        final String field = (String) i.next();
        final Method setMethod = bd.writableProps.get(field);
        if (setMethod != null) {
            try {
                final Class<?> param[] = setMethod.getParameterTypes();
                if (param.length != 1) {
                    throw new UnmarshallException("bean " + clazz.getName() + " method " + setMethod.getName()
                            + " does not have one arg");
                }
                tmp = ser.tryUnmarshall(state, param[0], jso.get(field));
                if (tmp != null) {
                    if (m == null) {
                        m = tmp;
                    } else {
                        m = m.max(tmp);
                    }
                }
            } catch (final UnmarshallException e) {
                throw new UnmarshallException("bean " + clazz.getName() + " " + e.getMessage(), e);
            } catch (final JSONException e) {
                throw new UnmarshallException("bean " + clazz.getName() + " " + e.getMessage(), e);
            }
        } else {
            mismatch++;
        }
    }
    if (m != null) {
        returnValue.setMismatch(m.max(new ObjectMatch(mismatch)).getMismatch());
    } else {
        returnValue.setMismatch(mismatch);
    }
    return returnValue;
}

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

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

    final JSONObject jso = (JSONObject) o;
    BeanData bd;//w ww  . ja  v  a 2 s.c o  m
    try {
        bd = getBeanData(clazz);
    } catch (final IntrospectionException e) {
        throw new UnmarshallException(clazz.getName() + " is not a bean", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("unmarshall", "instantiating " + clazz.getName());
    }
    Object instance;
    try {
        instance = clazz.newInstance();
    } catch (final InstantiationException e) {
        throw new UnmarshallException(
                "could not instantiate bean of type " + clazz.getName() + ", make sure it has a no argument "
                        + "constructor and that it is not an interface or " + "abstract class",
                e);
    } catch (final IllegalAccessException e) {
        throw new UnmarshallException("could not instantiate bean of type " + clazz.getName(), e);
    } catch (final RuntimeException e) {
        throw new UnmarshallException("could not instantiate bean of type " + clazz.getName(), e);
    }
    state.setSerialized(o, instance);
    final Object invokeArgs[] = new Object[1];
    Object fieldVal;
    final Iterator<?> i = jso.keys();
    while (i.hasNext()) {
        final String field = (String) i.next();
        final Method setMethod = bd.writableProps.get(field);
        if (setMethod != null) {
            try {
                final Class<?> param[] = setMethod.getParameterTypes();
                fieldVal = ser.unmarshall(state, param[0], jso.get(field));
            } catch (final UnmarshallException e) {
                throw new UnmarshallException(
                        "could not unmarshall field \"" + field + "\" of bean " + clazz.getName(), e);
            } catch (final JSONException e) {
                throw new UnmarshallException(
                        "could not unmarshall field \"" + field + "\" of bean " + clazz.getName(), e);
            }
            if (log.isDebugEnabled()) {
                log.debug("unmarshall", "invoking " + setMethod.getName() + "(" + fieldVal + ")");
            }
            invokeArgs[0] = fieldVal;
            try {
                setMethod.invoke(instance, invokeArgs);
            } catch (Throwable e) {
                if (e instanceof InvocationTargetException) {
                    e = ((InvocationTargetException) e).getTargetException();
                }
                throw new UnmarshallException("bean " + clazz.getName() + "can't invoke " + setMethod.getName()
                        + ": " + e.getMessage(), e);
            }
        }
    }
    return instance;
}

From source file:com.lottodroid.widgets.wikiarticle.WikiarticleHelper.java

/**
 * Read and return the content for a specific Wiktionary page. This makes a
 * lightweight API call, and trims out just the page content returned.
 * Because this call blocks until results are available, it should not be
 * run from a UI thread.//from w w  w  .  j  a  v a  2 s.c o m
 * 
 * @param title The exact title of the Wiktionary page requested.
 * @param expandTemplates If true, expand any wiki templates found.
 * @return Exact content of page.
 * @throws ApiException If any connection or server error occurs.
 * @throws ParseException If there are problems parsing the response.
 */
public static String getPageContent(String title, boolean expandTemplates) throws ApiException, ParseException {
    // Encode page title and expand templates if requested
    String encodedTitle = Uri.encode(title);
    String expandClause = expandTemplates ? WIKIARTICLE_EXPAND_TEMPLATES : "";

    // Query the API for content
    String content = getUrlContent(String.format(WIKIARTICLE_PAGE, encodedTitle, expandClause));
    try {
        // Drill into the JSON response to find the content body
        JSONObject response = new JSONObject(content);
        JSONObject query = response.getJSONObject("query");
        JSONObject pages = query.getJSONObject("pages");
        JSONObject page = pages.getJSONObject((String) pages.keys().next());
        JSONArray revisions = page.getJSONArray("revisions");
        JSONObject revision = revisions.getJSONObject(0);
        return revision.getString("*");
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response", e);
    }
}

From source file:org.ohmage.request.user.UserReadRequest.java

/**
 * Creates a JSONObject from the result object and responds with that 
 * object.//from  w w  w  .  j  a v a  2  s. c  o  m
 */
@Override
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    JSONObject metadata = new JSONObject();
    JSONObject jsonResult = new JSONObject();

    try {
        metadata.put(JSON_KEY_TOTAL_NUM_RESULTS, numResults);

        for (UserInformation userInformation : results) {
            JSONObject currResult = userInformation.toJson(false, false);

            UserPersonal personalInformation = userInformation.getPersonalInfo();
            if (personalInformation != null) {
                JSONObject personalJson = personalInformation.toJsonObject();

                @SuppressWarnings("unchecked")
                Iterator<String> personalJsonIter = personalJson.keys();
                while (personalJsonIter.hasNext()) {
                    String currKey = personalJsonIter.next();

                    currResult.put(currKey, personalJson.get(currKey));
                }
            }

            jsonResult.put(userInformation.getUsername(), currResult);
        }
    } catch (JSONException e) {
        LOGGER.error("There was an error building the respons object.");
        setFailed();
    }
    super.respond(httpRequest, httpResponse, metadata, jsonResult);
}

From source file:com.basho.riak.client.http.util.ClientUtils.java

/**
 * Convert a {@link JSONObject} to a map
 * // ww  w . ja  va 2s  . c o m
 * @param json
 *            {@link JSONObject} to convert
 * @return Map of the field names to string representations of the values
 */
@SuppressWarnings("rawtypes")
public static Map<String, String> jsonObjectAsMap(JSONObject json) {
    if (json == null)
        return null;

    Map<String, String> m = new HashMap<String, String>();
    for (Iterator iter = json.keys(); iter.hasNext();) {
        Object obj = iter.next();
        if (obj != null) {
            String key = obj.toString();
            m.put(key, json.optString(key));
        }
    }
    return m;
}

From source file:org.official.json.HTTP.java

/**
 * Convert a JSONObject into an HTTP header. A request header must contain
 * <pre>{//w w w .ja  va2 s.c  o  m
 *    Method: "POST" (for example),
 *    "Request-URI": "/" (for example),
 *    "HTTP-Version": "HTTP/1.1" (for example)
 * }</pre>
 * A response header must contain
 * <pre>{
 *    "HTTP-Version": "HTTP/1.1" (for example),
 *    "Status-Code": "200" (for example),
 *    "Reason-Phrase": "OK" (for example)
 * }</pre>
 * Any other members of the JSONObject will be output as HTTP fields.
 * The result will end with two CRLF pairs.
 * @param jo A JSONObject
 * @return An HTTP header string.
 * @throws JSONException if the object does not contain enough
 *  information.
 */
public static String toString(JSONObject jo) throws JSONException {
    Iterator<String> keys = jo.keys();
    String string;
    StringBuilder sb = new StringBuilder();
    if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
        sb.append(jo.getString("HTTP-Version"));
        sb.append(' ');
        sb.append(jo.getString("Status-Code"));
        sb.append(' ');
        sb.append(jo.getString("Reason-Phrase"));
    } else if (jo.has("Method") && jo.has("Request-URI")) {
        sb.append(jo.getString("Method"));
        sb.append(' ');
        sb.append('"');
        sb.append(jo.getString("Request-URI"));
        sb.append('"');
        sb.append(' ');
        sb.append(jo.getString("HTTP-Version"));
    } else {
        throw new JSONException("Not enough material for an HTTP header.");
    }
    sb.append(CRLF);
    while (keys.hasNext()) {
        string = keys.next();
        if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string)
                && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) {
            sb.append(string);
            sb.append(": ");
            sb.append(jo.getString(string));
            sb.append(CRLF);
        }
    }
    sb.append(CRLF);
    return sb.toString();
}

From source file:com.pimp.companionforband.fragments.cloud.ProfileFragment.java

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    profileTV = (TextView) view.findViewById(R.id.profile_textview);
    devicesTV = (TextView) view.findViewById(R.id.devices_textview);

    RequestQueue queue = Volley.newRequestQueue(getContext());

    JsonObjectRequest profileRequest = new JsonObjectRequest(Request.Method.GET,
            CloudConstants.BASE_URL + CloudConstants.Profile_URL, null, new Response.Listener<JSONObject>() {
                @Override/*from   w  w  w. java  2 s  . c o m*/
                public void onResponse(JSONObject response) {
                    JsonFlattener parser = new JsonFlattener();
                    CSVWriter writer = new CSVWriter();
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                    try {
                        List<LinkedHashMap<String, String>> flatJson = parser.parseJson(response.toString());
                        writer.writeAsCSV(flatJson,
                                path + File.separator + "CompanionForBand" + File.separator + "profile.csv");
                    } catch (Exception e) {
                        Log.e("profileFragParseJson", e.toString());
                    }

                    Iterator<String> stringIterator = response.keys();
                    while (stringIterator.hasNext()) {
                        try {
                            String key = stringIterator.next();
                            profileTV.append(UIUtils.splitCamelCase(key) + " : ");
                            profileTV.append(response.get(key).toString() + "\n\n");
                        } catch (Exception e) {
                            profileTV.append(e.toString());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    profileTV.setText(error.getMessage());
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization",
                    "Bearer " + MainActivity.sharedPreferences.getString("access_token", "hi"));

            return headers;
        }
    };

    JsonObjectRequest devicesRequest = new JsonObjectRequest(Request.Method.GET,
            CloudConstants.BASE_URL + CloudConstants.Devices_URL, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Iterator<String> stringIterator = response.keys();
                    while (stringIterator.hasNext()) {
                        try {
                            String key = stringIterator.next();
                            if (key.equals("deviceProfiles")) {
                                JSONArray jsonArray = response.getJSONArray("deviceProfiles");

                                JsonFlattener parser = new JsonFlattener();
                                CSVWriter writer = new CSVWriter();
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                                try {
                                    List<LinkedHashMap<String, String>> flatJson = parser
                                            .parseJson(jsonArray.toString());
                                    writer.writeAsCSV(flatJson, path + File.separator + "CompanionForBand"
                                            + File.separator + "devices.csv");
                                } catch (Exception e) {
                                    Log.e("profileDevicesParseJson", e.toString());
                                }

                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject device = jsonArray.getJSONObject(i);
                                    Iterator<String> iterator = device.keys();
                                    while (iterator.hasNext()) {
                                        key = iterator.next();
                                        devicesTV.append(UIUtils.splitCamelCase(key) + " : ");
                                        devicesTV.append(device.get(key).toString() + "\n");
                                    }
                                    devicesTV.append("\n\n");
                                }
                            } else {
                                devicesTV.append(UIUtils.splitCamelCase(key) + " : ");
                                devicesTV.append(response.get(key).toString() + "\n\n");
                            }
                        } catch (Exception e) {
                            devicesTV.append(e.toString());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    devicesTV.setText(error.getMessage());
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization",
                    "Bearer " + MainActivity.sharedPreferences.getString("access_token", "hi"));

            return headers;
        }
    };

    queue.add(profileRequest);
    queue.add(devicesRequest);
}

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

/**
 * Create a new redpen for the JSON object.
 * @param requestJSON the JSON contains configurations
 * @return a configured redpen instance//  ww  w.j av  a  2s  .  co  m
 */
public RedPen getRedPenFromJSON(JSONObject requestJSON) {
    String lang = "en";

    Map<String, Map<String, String>> properties = new HashMap<>();
    JSONObject config = null;
    if (requestJSON.has("config")) {
        try {
            config = requestJSON.getJSONObject("config");
            lang = getOrDefault(config, "lang", "en");
            if (config.has("validators")) {
                JSONObject validators = config.getJSONObject("validators");
                Iterator keyIter = validators.keys();
                while (keyIter.hasNext()) {
                    String validator = String.valueOf(keyIter.next());
                    Map<String, String> props = new HashMap<>();
                    properties.put(validator, props);
                    JSONObject validatorConfig = validators.getJSONObject(validator);
                    if ((validatorConfig != null) && validatorConfig.has("properties")) {
                        JSONObject validatorProps = validatorConfig.getJSONObject("properties");
                        Iterator propsIter = validatorProps.keys();
                        while (propsIter.hasNext()) {
                            String propname = String.valueOf(propsIter.next());
                            props.put(propname, validatorProps.getString(propname));
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("Exception when processing JSON properties", e);
        }
    }

    RedPen redPen = this.getRedPen(lang, properties);

    // override any symbols
    if ((config != null) && config.has("symbols")) {
        try {
            JSONObject symbols = config.getJSONObject("symbols");
            Iterator keyIter = symbols.keys();
            while (keyIter.hasNext()) {
                String symbolName = String.valueOf(keyIter.next());
                try {
                    SymbolType symbolType = SymbolType.valueOf(symbolName);
                    JSONObject symbolConfig = symbols.getJSONObject(symbolName);
                    Symbol originalSymbol = redPen.getConfiguration().getSymbolTable().getSymbol(symbolType);
                    if ((originalSymbol != null) && (symbolConfig != null) && symbolConfig.has("value")) {
                        String value = symbolConfig.has("value") ? symbolConfig.getString("value")
                                : String.valueOf(originalSymbol.getValue());
                        boolean spaceBefore = symbolConfig.has("before_space")
                                ? symbolConfig.getBoolean("before_space")
                                : originalSymbol.isNeedBeforeSpace();
                        boolean spaceAfter = symbolConfig.has("after_space")
                                ? symbolConfig.getBoolean("after_space")
                                : originalSymbol.isNeedAfterSpace();
                        String invalidChars = symbolConfig.has("invalid_chars")
                                ? symbolConfig.getString("invalid_chars")
                                : String.valueOf(originalSymbol.getInvalidChars());
                        if ((value != null) && !value.isEmpty()) {
                            redPen.getConfiguration().getSymbolTable().overrideSymbol(new Symbol(symbolType,
                                    value.charAt(0), invalidChars, spaceBefore, spaceAfter));
                        }
                    }

                } catch (IllegalArgumentException iae) {
                    LOG.error("Ignoring unknown SymbolType " + symbolName);
                }
            }
        } catch (Exception e) {
            LOG.error("Exception when processing JSON symbol overrides", e);
        }
    }

    return redPen;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Given a JSONObject, unmarhall it to an instance of the given class.
 *
 * @param jsonObj JSON string to unmarshall.
 * @param cls Return an instance of this class. Must be either public class
 *            or private static class. Inner class will not work.
 * @param <T> Same type as cls.//from   w  w w  .  j ava 2  s.  c  o  m
 * @return An instance of class given by cls.
 * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
 */
public static <T> T JSONToObj(JSONObject jsonObj, Class<T> cls) {
    T result = null;

    try {
        Constructor<T> constructor = cls.getDeclaredConstructor();
        constructor.setAccessible(true);
        result = (T) constructor.newInstance();
        Iterator<?> i = jsonObj.keys();

        while (i.hasNext()) {
            String k = (String) i.next();
            Object val = jsonObj.get(k);

            try {
                Field field = cls.getField(k);
                Object converted = valToType(val, field.getGenericType());

                if (converted == null) {
                    if (!field.getType().isPrimitive()) {
                        field.set(result, null);
                    } else {
                        throw new TypeMismatchException(
                                String.format("Type %s cannot be set to null.", field.getType()));
                    }
                } else {
                    if (converted instanceof List && field.getType().isAssignableFrom(List.class)) {
                        // Class can define their own favorite
                        // implementation of List. In which case the field
                        // still need to be defined as List, but it can be
                        // initialized with a placeholder instance of any of
                        // the List implementations (eg. ArrayList).
                        Object existing = field.get(result);
                        if (existing != null) {
                            ((List<?>) existing).clear();

                            // Just because I don't want javac to complain
                            // about unsafe operations. So I'm gonna use
                            // more reflection, HA!
                            Method addAll = existing.getClass().getMethod("addAll", Collection.class);
                            addAll.invoke(existing, converted);
                        } else {
                            field.set(result, converted);
                        }
                    } else {
                        field.set(result, converted);
                    }
                }
            } catch (NoSuchFieldException e) {
                // Ignore.
            } catch (IllegalAccessException e) {
                // Ignore.
            } catch (IllegalArgumentException e) {
                // Ignore.
            }
        }
    } catch (JSONException e) {
        throw new ParserException(e);
    } catch (NoSuchMethodException e) {
        throw new ClassInstantiationException("Failed to retrieve constructor for " + cls.toString()
                + ", make sure it's not an inner class.");
    } catch (InstantiationException e) {
        throw new ClassInstantiationException(cls);
    } catch (IllegalAccessException e) {
        throw new ClassInstantiationException(cls);
    } catch (InvocationTargetException e) {
        throw new ClassInstantiationException(cls);
    }

    return result;
}

From source file:edu.mit.scratch.ScratchUser.java

@Deprecated
public List<ScratchProject> getProjects() throws ScratchUserException { // DEPRECATED
    final List<ScratchProject> ids = new ArrayList<>();

    try {/*from  w w w.j av  a  2  s . com*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(debug);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://api.scratch.mit.edu/users/" + this.getUsername() + "/projects")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/")
                .addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONArray jsonOBJ2 = new JSONArray(result.toString().trim());

        for (int i = 0; i < jsonOBJ2.length(); i++) {
            final JSONObject jsonOBJ = jsonOBJ2.getJSONObject(i);

            final Iterator<?> keys = jsonOBJ.keys();

            while (keys.hasNext()) {
                final String key = "" + keys.next();
                final Object o = jsonOBJ.get(key);
                final String val = "" + o;

                if (key.equalsIgnoreCase("id"))
                    ids.add(new ScratchProject(Integer.parseInt(val)));
            }
        }

        return ids;
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }
}