Example usage for com.google.gson JsonElement getAsJsonArray

List of usage examples for com.google.gson JsonElement getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonArray.

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.hybris.mobile.lib.http.converter.JsonDataConverter.java

License:Open Source License

/**
 * @param data     String of character to be parsed
 * @param property Attributes to be parse
 * @param element  JSON element to get data from
 * @return List of String//from  ww w.ja v a  2 s. c o m
 */
protected List<String> getValuesFromPropertyElement(String data, String property, String element,
        boolean recursive) {
    List<String> listToReturn = new ArrayList<>();

    if (data == null) {
        throw new IllegalArgumentException();
    }

    JsonParser parser = new JsonParser();

    JsonArray jsonArray;
    JsonElement jsonElement;

    try {
        if (StringUtils.isNotBlank(property)) {
            jsonElement = parser.parse(data).getAsJsonObject().get(property);
        } else {
            jsonElement = parser.parse(data);
        }

        if (jsonElement != null) {
            if (jsonElement.isJsonArray()) {
                jsonArray = jsonElement.getAsJsonArray();
            } else {
                jsonArray = new JsonArray();
                jsonArray.add(jsonElement);
            }

            if (jsonArray != null) {

                for (JsonElement currentJsonElement : jsonArray) {

                    if (StringUtils.isNotBlank(element)) {
                        if (recursive) {
                            try {
                                listToReturn.addAll(getValuesFromPropertyElement(currentJsonElement.toString(),
                                        property, element, recursive));
                            } catch (NoSuchElementException e) {
                                Log.d(TAG, "End of getting the recursive property " + property + ".");
                            }
                        }

                        currentJsonElement = currentJsonElement.getAsJsonObject().get(element);
                    }

                    if (currentJsonElement != null) {
                        if (currentJsonElement.isJsonPrimitive()) {
                            listToReturn.add(currentJsonElement.getAsString());
                        } else {
                            listToReturn.add(currentJsonElement.toString());
                        }
                    } else {
                        Log.d(TAG, "No data found for element " + element + ".");
                    }

                }

            }

        } else {
            Log.d(TAG, "No data found on " + data + " for property " + property + ".");
        }
    } catch (Exception e) {
        Log.e(TAG, "Error parsing the data " + data + " for property " + property + " and element " + element
                + ".");
        throw new NoSuchElementException("Error parsing the data " + data + " for property " + property
                + " and element " + element + ".");
    }

    return listToReturn;

}

From source file:com.ibasco.agql.core.AbstractWebApiInterface.java

License:Open Source License

/**
 * Converts the underlying processed content to a {@link com.google.gson.JsonObject} instance
 *///w w w  .  j  a  v  a  2s  .c om
@SuppressWarnings("unchecked")
private <A> A postProcessConversion(Res response) {
    log.debug("ConvertToJson for Response = {}, {}", response.getMessage().getStatusCode(),
            response.getMessage().getHeaders());
    JsonElement processedElement = response.getProcessedContent();
    if (processedElement != null) {
        if (processedElement.isJsonObject())
            return (A) processedElement.getAsJsonObject();
        else if (processedElement.isJsonArray())
            return (A) processedElement.getAsJsonArray();
    }
    throw new AsyncGameLibUncheckedException("No parsed content found for response" + response);
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.adapters.StoreAppPcRequirementsDeserializer.java

License:Open Source License

@Override
public StoreAppPcRequirements deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    StoreAppPcRequirements requirements = new StoreAppPcRequirements();

    //Fail fast and just return an empty value
    if (json.isJsonNull() || json.isJsonPrimitive()
            || (json.isJsonArray() && json.getAsJsonArray().size() == 0)) {
        return requirements;
    }/* w  w  w .  java 2s .  c  om*/

    JsonObject object = json.getAsJsonObject();
    if (object.has("minimum")) {
        requirements.setMinimum(object.get("minimum").getAsString());
    }
    if (object.has("recommended")) {
        requirements.setRecommended(object.get("recommended").getAsString());
    }
    return requirements;
}

From source file:com.ibm.common.activitystreams.internal.ASObjectAdapter.java

License:Apache License

/**
 * Method deserialize.//from  ww w  . ja  v  a2  s  .  co  m
 * @param element JsonElement
 * @param type Type
 * @param context JsonDeserializationContext
 * @return ASObject 
 * @throws JsonParseException
 * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) 
 **/
public final ASObject deserialize(JsonElement element, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject obj = (JsonObject) element;
    ASObject.AbstractBuilder<?, ?> builder = null;
    Model propMap = null;
    TypeValue tv = null;

    if (knowsType(type)) {
        builder = builderFor(type);
        propMap = modelFor(type);
    } else {
        if (obj.has("objectType")) {
            tv = context.deserialize(obj.get("objectType"), TypeValue.class);
            @SuppressWarnings("rawtypes")
            Class<? extends ASObject.AbstractBuilder> _class = schema.builderForObjectTypeOrClass(tv.id(),
                    (Class) type);
            if (_class != null) {
                propMap = schema.forObjectClassOrType(_class, tv.id());
                if (!_class.isInterface()) {
                    try {
                        builder = _class.getConstructor(String.class).newInstance(tv.id());
                    } catch (Throwable t) {
                        try {
                            builder = _class.newInstance();
                            builder.set("objectType", tv);
                        } catch (Throwable t2) {
                            builder = Makers.object(tv);
                        }
                    }
                } else
                    builder = Makers.object(tv);
            } else {
                builder = Makers.object(tv);
                propMap = schema.forObjectClassOrType(ASObject.Builder.class, tv.id());
            }
        } else {
            if (obj.has("verb") && (obj.has("actor") || obj.has("object") || obj.has("target"))) {
                builder = activity();
                propMap = schema.forObjectClassOrType(Activity.Builder.class, "activity");
            } else if (obj.has("items")) {
                builder = collection();
                propMap = schema.forObjectClassOrType(Collection.Builder.class, "collection");
            } else {
                @SuppressWarnings("rawtypes")
                Class<? extends ASObject.AbstractBuilder> _class = schema.builderFor((Class) type);
                if (_class != null) {
                    if (!_class.isInterface()) {
                        try {
                            builder = _class.newInstance();
                        } catch (Throwable t) {
                            builder = object();
                        }
                    } else
                        builder = object();
                }
                if (builder == null)
                    builder = object(); // anonymous
                propMap = schema.forObjectClass(builder.getClass());
                propMap = propMap != null ? propMap : schema.forObjectClass(ASObject.Builder.class);
            }
        }
    }

    for (Entry<String, JsonElement> entry : obj.entrySet()) {
        String name = entry.getKey();
        if (name.equalsIgnoreCase("objectType"))
            continue;
        Class<?> _class = propMap.get(name);
        JsonElement val = entry.getValue();
        if (val.isJsonPrimitive())
            builder.set(name, _class != null ? context.deserialize(val, _class)
                    : primConverter.convert(val.getAsJsonPrimitive()));
        else if (val.isJsonArray()) {
            builder.set(name,
                    LinkValue.class.isAssignableFrom(_class != null ? _class : Object.class)
                            ? context.deserialize(val, LinkValue.class)
                            : convert(val.getAsJsonArray(), _class, context, builder()));
        } else if (val.isJsonObject())
            builder.set(name, context.deserialize(val, propMap.has(name) ? propMap.get(name) : ASObject.class));
    }
    return builder.get();

}

From source file:com.ibm.common.activitystreams.internal.ASObjectAdapter.java

License:Apache License

/**
 * Method processArray.//from   w w w. j a v a 2 s  . com
 * @param arr JsonArray
 * @param _class Class<?>
 * @param context JsonDeserializationContext
 * @param list ImmutableList.Builder<Object>
 */
private void processArray(JsonArray arr, Class<?> _class, JsonDeserializationContext context,
        ImmutableList.Builder<Object> list) {
    for (JsonElement mem : arr) {
        if (mem.isJsonPrimitive())
            list.add(_class != null ? context.deserialize(mem, _class)
                    : primConverter.convert(mem.getAsJsonPrimitive()));
        else if (mem.isJsonObject())
            list.add(context.deserialize(mem, _class != null ? _class : ASObject.class));
        else if (mem.isJsonArray())
            list.add(convert(mem.getAsJsonArray(), _class, context, builder()));
    }
}

From source file:com.ibm.common.activitystreams.internal.LinkValueAdapter.java

License:Apache License

/**
 * Method deserialize.//from  w  w  w  .  j  ava2 s .  c  o  m
 * @param el JsonElement
 * @param type Type
 * @param context JsonDeserializationContext
        
        
        
 * @return LinkValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public LinkValue deserialize(JsonElement el, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    checkArgument(el.isJsonArray() || el.isJsonObject() || el.isJsonPrimitive());
    if (el.isJsonArray()) {
        LinkValue.ArrayLinkValue.Builder builder = linkValues();
        for (JsonElement aryel : el.getAsJsonArray())
            builder.add(context.<LinkValue>deserialize(aryel, LinkValue.class));
        return builder.get();
    } else if (el.isJsonObject()) {
        JsonObject obj = el.getAsJsonObject();
        if (obj.has("objectType")) {
            TypeValue tv = context.deserialize(obj.get("objectType"), TypeValue.class);
            Model pMap = schema.forObjectType(tv.id());
            return context.deserialize(el, pMap != null && pMap.type() != null ? pMap.type() : ASObject.class);
        } else {
            return context.deserialize(el, ASObject.class);
        }
    } else {
        JsonPrimitive prim = el.getAsJsonPrimitive();
        checkArgument(prim.isString());
        return linkValue(prim.getAsString());
    }
}

From source file:com.ibm.common.activitystreams.internal.MultimapAdapter.java

License:Apache License

/**
 * Method arraydes.//w  w w .jav  a2  s  . co m
 * @param array JsonArray
 * @param context JsonDeserializationContext
        
 * @return ImmutableList<Object> */
protected static ImmutableList<Object> arraydes(JsonArray array, JsonDeserializationContext context) {
    ImmutableList.Builder<Object> builder = ImmutableList.builder();
    for (JsonElement child : array)
        if (child.isJsonArray())
            builder.add(arraydes(child.getAsJsonArray(), context));
        else if (child.isJsonObject())
            builder.add(context.deserialize(child, ASObject.class));
        else if (child.isJsonPrimitive())
            builder.add(primConverter.convert(child.getAsJsonPrimitive()));
    return builder.build();
}

From source file:com.ibm.common.activitystreams.internal.MultimapAdapter.java

License:Apache License

/**
 * Method deserialize./*from ww  w .  j av a2 s. c om*/
 * @param json JsonElement
 * @param typeOfT Type
 * @param context JsonDeserializationContext
        
        
        
 * @return Multimap * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public Multimap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    ImmutableMultimap.Builder mm = ImmutableMultimap.builder();
    JsonObject obj = json.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String key = entry.getKey();
        JsonElement val = entry.getValue();
        if (val.isJsonArray()) {
            for (JsonElement el : val.getAsJsonArray()) {
                if (el.isJsonArray())
                    mm.put(key, arraydes(el.getAsJsonArray(), context));
                else if (el.isJsonObject())
                    mm.put(key, context.deserialize(el, ASObject.class));
                else if (el.isJsonPrimitive())
                    mm.put(key, primConverter.convert(el.getAsJsonPrimitive()));
            }
        } else if (val.isJsonObject()) {
            mm.put(key, context.deserialize(val, ASObject.class));
        } else if (val.isJsonPrimitive()) {
            mm.put(key, primConverter.convert(val.getAsJsonPrimitive()));
        }
    }
    return mm.build();
}

From source file:com.ibm.devops.dra.AbstractDevOpsAction.java

License:Open Source License

/**
 * Get a list of policies that belong to an org
 * @param token//from  ww  w.java2  s. co m
 * @param orgName
 * @return
 */

public static ListBoxModel getPolicyList(String token, String orgName, String toolchainName, String environment,
        Boolean debug_mode) {

    // get all jenkins job
    ListBoxModel emptybox = new ListBoxModel();
    emptybox.add("", "empty");

    String url = choosePoliciesUrl(environment);

    try {
        url = url.replace("{org_name}", URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20"));
        url = url.replace("{toolchain_name}",
                URLEncoder.encode(toolchainName, "UTF-8").replaceAll("\\+", "%20"));
        if (debug_mode) {
            LOGGER.info("GET POLICIES URL:" + url);
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        httpGet = addProxyInformation(httpGet);

        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;
        response = httpClient.execute(httpGet);
        String resStr = EntityUtils.toString(response.getEntity());

        if (debug_mode) {
            LOGGER.info("RESPONSE FROM GET POLICIES URL:" + response.getStatusLine().toString());
        }
        if (response.getStatusLine().toString().contains("200")) {
            // get 200 response
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(resStr);
            JsonArray jsonArray = element.getAsJsonArray();

            ListBoxModel model = new ListBoxModel();

            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject obj = jsonArray.get(i).getAsJsonObject();
                String name = String.valueOf(obj.get("name")).replaceAll("\"", "");
                model.add(name, name);
            }
            if (debug_mode) {
                LOGGER.info("POLICY LIST:" + model);
                LOGGER.info("#######################");
            }
            return model;
        } else {
            if (debug_mode) {
                LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: "
                        + response.getStatusLine().toString());
            }
            return emptybox;
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return emptybox;
}

From source file:com.ibm.g11n.pipeline.client.ServiceAccount.java

License:Open Source License

/**
 * Returns an instance of ServiceAccount from the VCAP_SERVICES environment
 * variable./*from  w ww  . j  av a2  s .c  om*/
 * <p>
 * When <code>serviceInstanceName</code> is null, this method returns
 * a ServiceAccount for the first valid IBM Globlization Pipeline service instance.
 * If <code>serviceInstanceName</code> is not null, this method look up a
 * matching service entry, and returns a ServiceAccount for the matching entry.
 * If <code>serviceInstanceName</code> is not null and there is no match,
 * this method returns null.
 * 
 * @param serviceName
 *          The name of IBM Globalization Pipeline service. If null,
 *          the first service with a name matching GP_SERVICE_NAME_PATTERN
 *          will be used.
 * @param serviceInstanceName
 *          The name of IBM Globalization Pipeline service instance, or null
 *          designating the first available service instance.
 * @return  An instance of ServiceAccount for the specified service instance
 *          name, or null.
 */
private static ServiceAccount getInstanceByVcapServices(String serviceName, String serviceInstanceName) {
    Map<String, String> env = System.getenv();
    String vcapServices = env.get("VCAP_SERVICES");
    if (vcapServices == null) {
        return null;
    }

    try {
        JsonObject obj = new JsonParser().parse(vcapServices).getAsJsonObject();

        // When service name is specified,
        // this method returns only a matching entry
        if (serviceName != null) {
            JsonElement elem = obj.get(serviceName);
            if (elem != null && elem.isJsonArray()) {
                return parseToServiceAccount(elem.getAsJsonArray(), serviceInstanceName);
            }
        }

        // Otherwise, lookup a valid entry with a name matching
        // the default pattern GP_SERVICE_NAME_PATTERN.
        for (Entry<String, JsonElement> entry : obj.entrySet()) {
            String name = entry.getKey();
            JsonElement elem = entry.getValue();
            if (elem.isJsonArray() && GP_SERVICE_NAME_PATTERN.matcher(name).matches()) {
                ServiceAccount account = parseToServiceAccount(elem.getAsJsonArray(), serviceInstanceName);
                if (account != null) {
                    return account;
                }
            }
        }
    } catch (JsonParseException e) {
        // Fall through - will return null
    }

    return null;
}