Example usage for com.google.gson JsonArray iterator

List of usage examples for com.google.gson JsonArray iterator

Introduction

In this page you can find the example usage for com.google.gson JsonArray iterator.

Prototype

public Iterator<JsonElement> iterator() 

Source Link

Document

Returns an iterator to navigate the elements of the array.

Usage

From source file:co.com.codesoftware.facturacion.ajax.controlador.AjaxControllerFacturacion.java

public ArrayList<ProductosFactEntitiy> generaListaProductos() {
    JsonElement json = new JsonParser().parse(this.productosArray);
    JsonArray array = json.getAsJsonArray();
    Iterator iterator = array.iterator();
    ArrayList<ProductosFactEntitiy> productosList = null;
    while (iterator.hasNext()) {
        if (productosList == null) {
            productosList = new ArrayList<>();
        }/* w w w  .j  a  va 2s.  c o  m*/
        JsonElement json2 = (JsonElement) iterator.next();
        Gson gson = new Gson();
        ProductosFactEntitiy prod = gson.fromJson(json2, ProductosFactEntitiy.class);
        productosList.add(prod);
    }
    return productosList;
}

From source file:com.appdynamics.extensions.couchbase.CouchBaseWrapper.java

License:Apache License

private void populateOtherBucketMetricsMapHelper(String metricName, JsonArray replicationStats,
        Map<String, Double> bucketMetrics) {
    if (replicationStats != null) {
        Iterator<JsonElement> stats = replicationStats.iterator();
        while (stats.hasNext()) {
            try {
                Double value = stats.next().getAsDouble();
                bucketMetrics.put(metricName, value);
                break;
            } catch (ClassCastException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug(/*from   ww  w . j a v a  2  s  . c o  m*/
                            String.format("Incorrect value type retrieved for %s, ignoring...", metricName),
                            ex);
                }
            } catch (IllegalStateException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            String.format("Incorrect value type retrieved for %s, ignoring...", metricName),
                            ex);
                }
            }
        }
    }

}

From source file:com.appspot.bitlyminous.gateway.FoursquareGateway.java

License:Apache License

/**
 * Gets the nearby venues.// w  w w.  ja v a  2s .  c  o  m
 * 
 * @param location the location
 * @param query the query
 * @param limit the limit
 * 
 * @return the nearby venues
 */
public List<Venue> getNearbyVenues(GeoLocation location, String query, int limit) {
    GatewayApiUrlBuilder builder = createApiUrlBuilder(ApplicationConstants.FOURSQUARE_NEAR_BY_VENUES_URL);
    String apiUrl = builder.withParameter("geolat", String.valueOf(location.getLatitude()))
            .withParameter("geolong", String.valueOf(location.getLongitude()))
            .withParameter("l", String.valueOf(limit)).withParameter("q", query).buildUrl();
    JsonObject json = parseJson(callApiGet(apiUrl)).getAsJsonObject();
    JsonArray groups = json.get("groups").getAsJsonArray();
    if (groups.iterator().hasNext()) {
        return unmarshall(new TypeToken<List<Venue>>() {
        }, groups.iterator().next().getAsJsonObject().get("venues"));
    } else {
        return new ArrayList<Venue>();
    }
}

From source file:com.balajeetm.mystique.core.lever.MystiqueLever.java

License:Open Source License

/**
 * Sets the field of a json source.//  w w  w.  j a v a  2  s . co m
 *
 * @param resultWrapper the json object that wraps the result json. The result is wrapped to
 *     ensure it passed across by reference and fields are updated appropriately
 * @param to the jPath json array defining the full qualified json path to the destination field
 *     where the value must be set
 * @param value the json value that needs to be set to the destination. This can be an Object,
 *     Array or a Primitive
 * @param aces the pre-processed dependency list in the form of key value pair (json)
 * @param optional the flag that determines if a null value must be set in the destination. If
 *     optional is TRUE, null values are not set in the destination
 * @return the json result wraper object which contains the result in the field called "result"
 */
public JsonObject set(JsonObject resultWrapper, JsonArray to, JsonElement value, JsonObject aces,
        Boolean optional) {

    /**
     * Holding a mutex on result wrapper and not making the method synchronized because, when
     * multiple unrelated threads might be calling mystique for transformation. The resource of
     * contention is only the result wrapper
     */
    synchronized (resultWrapper) {
        if (optional && isNull(value)) {
            // Do Not update result wrapper
            return resultWrapper;
        }
        if (isNotNull(to)) {
            JsonElement result = resultWrapper.get(MystiqueConstants.RESULT);
            JsonElement field = result;
            if (to.size() > 0) {
                JsonElement previousPath = null;
                JsonElement currentPath = null;
                Iterator<JsonElement> iterator = to.iterator();
                if (iterator.hasNext()) {
                    previousPath = getPathField(iterator.next(), aces);
                }

                while (iterator.hasNext()) {
                    currentPath = getPathField(iterator.next(), aces);

                    // get the field
                    field = getRepleteField(field, previousPath, currentPath);
                    result = updateResult(result, field);
                    field = isNumber(previousPath) ? field.getAsJsonArray().get(previousPath.getAsInt())
                            : field.getAsJsonObject().get(previousPath.getAsString());
                    previousPath = currentPath;
                }

                field = setField(field, previousPath, value);
                result = updateResult(result, field);
            } else {
                result = merge(result, value);
            }
            resultWrapper.add(MystiqueConstants.RESULT, result);
        }
        return resultWrapper;
    }
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Sets the json element at the specified jpath.
 *
 * @param source the source/*  w  w  w  . ja  v  a2 s.c o  m*/
 * @param jpath the fully qualified json path to the field required. eg set({'a': {'b': {'c': [1,
 *     2, 3, 4]}}}, ["a", "b" "c", 1, 5]) is {'a': {'b': {'c': [1, 5, 3, 4]}}}. Array indexes need
 *     to be specified as numerals. Strings are always presumed to be field names.
 * @param value the value
 * @return the json element
 */
public JsonElement set(JsonElement source, JsonArray jpath, JsonElement value) {
    JsonElement result = JsonNull.INSTANCE;
    if (isNotNull(jpath)) {
        result = source;
        JsonElement field = result;
        if (jpath.size() > 0) {
            JsonElement previousPath = null;
            JsonElement currentPath = null;
            Iterator<JsonElement> iterator = jpath.iterator();
            if (iterator.hasNext()) {
                previousPath = iterator.next();
            }

            while (iterator.hasNext()) {
                currentPath = iterator.next();
                // get the field
                field = getRepleteField(field, previousPath, currentPath);
                result = updateResult(result, field);
                field = isNumber(previousPath) ? field.getAsJsonArray().get(previousPath.getAsInt())
                        : field.getAsJsonObject().get(previousPath.getAsString());
                previousPath = currentPath;
            }

            field = setField(field, previousPath, value);
        }
    }
    return result;
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.PathParser.java

License:Apache License

@Override
public Path apply(JsonElement json) {
    if (json == null || !json.isJsonObject()) {
        return null;
    }/*from   www . java  2 s .  co  m*/
    JsonObject jsonObject = json.getAsJsonObject();
    JsonArray array = jsonObject.getAsJsonArray("components");
    String[] components = new String[array.size()];
    Iterator<JsonElement> it = array.iterator();
    int i = 0;
    while (it.hasNext()) {
        components[i++] = it.next().getAsString();
    }

    return new Path(components);
}

From source file:com.cdancy.artifactory.rest.fallbacks.ArtifactoryFallbacks.java

License:Apache License

public static RequestStatus createPromoteBuildFromError(String message) {
    List<Message> messages = new ArrayList<>();
    List<Error> errors = new ArrayList<>();

    JsonReader reader = new JsonReader(new StringReader(message));
    reader.setLenient(true);//from  ww w.  ja  va  2  s  .c o  m

    JsonElement possibleMessages = parser.parse(reader).getAsJsonObject().get("messages");
    if (possibleMessages != null) {
        JsonArray jsonArray = possibleMessages.getAsJsonArray();
        Iterator<JsonElement> iter = jsonArray.iterator();
        while (iter.hasNext()) {
            JsonElement jsonElement = iter.next();
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            Message mess = Message.create(jsonObject.get("level").getAsString(),
                    jsonObject.get("message").getAsString());
            messages.add(mess);
        }
    }

    JsonElement possibleErrors = parser.parse(message).getAsJsonObject().get("errors");
    if (possibleErrors != null) {
        JsonArray jsonArray = possibleErrors.getAsJsonArray();
        Iterator<JsonElement> iter = jsonArray.iterator();
        while (iter.hasNext()) {
            JsonElement jsonElement = iter.next();
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            Error error = Error.create(jsonObject.get("status").getAsInt(),
                    jsonObject.get("message").getAsString());
            errors.add(error);
        }
    }

    return RequestStatus.create(messages, errors);
}

From source file:com.cdancy.bitbucket.rest.fallbacks.BitbucketFallbacks.java

License:Apache License

/**
 * Parse list of Error's from output./*from w ww .  ja va  2 s.c  o m*/
 *
 * @param output json containing errors hash
 * @return List of Error's or empty list if none could be found
 */
public static List<Error> getErrors(String output) {
    JsonElement element = parser.parse(output);
    JsonObject object = element.getAsJsonObject();
    JsonArray errorsArray = object.get("errors").getAsJsonArray();

    List<Error> errors = Lists.newArrayList();
    Iterator<JsonElement> it = errorsArray.iterator();
    while (it.hasNext()) {
        JsonObject obj = it.next().getAsJsonObject();
        JsonElement context = obj.get("context");
        JsonElement message = obj.get("message");
        JsonElement exceptionName = obj.get("exceptionName");
        Error error = Error.create(!context.isJsonNull() ? context.getAsString() : null,
                !message.isJsonNull() ? message.getAsString() : null,
                !exceptionName.isJsonNull() ? exceptionName.getAsString() : null);
        errors.add(error);
    }

    return errors;
}

From source file:com.cloud.agent.transport.ArrayTypeAdaptor.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public T[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonArray array = json.getAsJsonArray();
    Iterator<JsonElement> it = array.iterator();
    ArrayList<T> cmds = new ArrayList<T>();
    while (it.hasNext()) {
        JsonObject element = (JsonObject) it.next();
        Map.Entry<String, JsonElement> entry = element.entrySet().iterator().next();

        String name = s_pkg + entry.getKey();
        Class<?> clazz;/*from   ww w. j a  v a2s.c o  m*/
        try {
            clazz = Class.forName(name);
        } catch (ClassNotFoundException e) {
            throw new CloudRuntimeException("can't find " + name);
        }
        T cmd = (T) _gson.fromJson(entry.getValue(), clazz);
        cmds.add(cmd);
    }
    Class<?> type = ((Class<?>) typeOfT).getComponentType();
    T[] ts = (T[]) Array.newInstance(type, cmds.size());
    return cmds.toArray(ts);
}

From source file:com.cloudbees.gasp.activity.GaspRESTLoaderActivity.java

License:Apache License

@Override
public void onLoadFinished(Loader<RESTLoader.RESTResponse> loader, RESTLoader.RESTResponse data) {
    int code = data.getCode();
    String json = data.getData();

    // Check to see if we got an HTTP 200 code and have some data.
    if (code == 200 && !json.equals("")) {

        Log.i(TAG, "RESTLoader returns:" + json);

        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(json).getAsJsonArray();
        Iterator<JsonElement> reviews = array.iterator();

        mAdapter.clear();//from   w w  w .  j  av  a 2 s.  com

        while (reviews.hasNext()) {
            mAdapter.add(reviews.next().toString());
        }

    } else {
        Toast.makeText(this, getResources().getString(R.string.gasp_network_error), Toast.LENGTH_SHORT).show();
    }
}