Example usage for com.google.gson JsonElement isJsonArray

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

Introduction

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

Prototype

public boolean isJsonArray() 

Source Link

Document

provides check for verifying if this element is an array or not.

Usage

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Create or update resources from remote JSON.
 *
 * @param json JsonObject/*from  ww  w. j a  v a2s . c om*/
 * @param resource Resource
 * @throws IOException exception
 * @throws RepositoryException exception
 */
private void createOrUpdateNodes(final ResourceResolver remoteAssetsResolver, final JsonObject json,
        final Resource resource) throws IOException, RepositoryException {
    for (Map.Entry<String, JsonElement> jsonEntry : json.entrySet()) {
        JsonElement jsonElement = jsonEntry.getValue();
        if (jsonElement.isJsonObject()) {
            createOrUpdateNodesForJsonObject(remoteAssetsResolver, jsonEntry.getKey(), resource);
        } else if (jsonElement.isJsonArray()) {
            setNodeArrayProperty(remoteAssetsResolver, jsonEntry.getKey(), jsonElement.getAsJsonArray(),
                    resource);
        } else {
            setNodeProperty(remoteAssetsResolver, jsonEntry.getKey(), json, resource);
        }
    }
}

From source file:com.ai2020lab.aiutils.common.JsonUtils.java

License:Apache License

/**
 * ?JsonArray/*from   w w w .j a va2 s .  c om*/
 *
 * @param jsonStr 
 * @return JsonArray
 */
public JsonArray stringToJsonArr(String jsonStr) {
    // JSON
    if (jsonStr == null || jsonStr.equals("")) {
        throw new IllegalArgumentException("???JsonArray?");
    }
    JsonElement jsonE = null;
    try {
        jsonE = jsonParser.parse(jsonStr);
    } catch (Exception e) {
        // JSON?JSON??
        LogUtils.e(TAG, " ??JsonArray");
    }
    if (jsonE == null || !jsonE.isJsonArray()) {
        // ?JsonArray?
        LogUtils.e(TAG, "??JsonArray??JsonArray?");
        return null;
    }
    return (JsonArray) jsonE;
}

From source file:com.apcb.utils.utils.HtmlTemplateReader.java

private SectionMatch readJson(JsonElement jsonElement, String from, SectionMatch sectionMatch) {
    //log.info(jsonElement.toString());
    //SectionMatch sectionMatchChild = new SectionMatch(from);
    if (jsonElement.isJsonArray()) {
        //log.info("JsonArray");
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            SectionMatch sectionMatchArrayLevel = new SectionMatch(sectionMatch.getName());
            sectionMatchArrayLevel.setIndex(i);
            sectionMatch.putChildens(readJson(jsonArray.get(i), from + "[" + i + "]", sectionMatchArrayLevel));
        }/*from w w  w  .j av a2 s  . c  om*/
    } else if (jsonElement.isJsonObject()) {
        //log.info("JsonObject");
        JsonObject jsonObject = jsonElement.getAsJsonObject(); //since you know it's a JsonObject
        Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();//will return members of your object
        for (Map.Entry<String, JsonElement> entry : entries) {
            //log.info(entry.getKey());
            sectionMatch.putChildens(readJson(jsonObject.get(entry.getKey()), from + "." + entry.getKey(),
                    new SectionMatch(entry.getKey())));
        }
    } else if (jsonElement.isJsonNull()) {
        log.info("JsonNull");
    } else if (jsonElement.isJsonPrimitive()) {
        //log.info("JsonPrimitive");
        String jsonVal = jsonElement.getAsString();
        //from+= "."+entry.getKey(); 
        sectionMatch.setValue(jsonVal);
        log.info(from + "=" + jsonVal);
    }

    return sectionMatch;
}

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

License:Apache License

/**
 * Gathers Bucket stats as Map of BucketName and Map of MetricName,
 * MetricValue/* w w  w.ja  v  a 2 s . c om*/
 * 
 * @param httpClient
 * @return Map<String, Map<String, Double>>
 */
public Map<String, Map<String, Double>> gatherBucketMetrics(SimpleHttpClient httpClient) {
    JsonElement bucketResponse = getResponse(httpClient, BUCKET_URI);
    Map<String, Map<String, Double>> bucketMetrics = new HashMap<String, Map<String, Double>>();
    if (bucketResponse != null && bucketResponse.isJsonArray()) {
        JsonArray bucketStats = bucketResponse.getAsJsonArray();
        bucketMetrics = populateBucketMetrics(bucketStats);
    }
    return bucketMetrics;
}

From source file:com.asakusafw.lang.inspection.json.PortReferenceAdapter.java

License:Apache License

@Override
public InspectionNode.PortReference deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonArray() == false) {
        throw new JsonParseException("port reference must be an array"); //$NON-NLS-1$
    }/*from ww  w  .  j  a v a2 s. co  m*/
    JsonArray array = (JsonArray) json;
    if (array.size() != 2) {
        throw new JsonParseException("port reference must have just 2 elements"); //$NON-NLS-1$
    }
    String nodeId = array.get(0).getAsString();
    String portId = array.get(1).getAsString();
    return new PortReference(nodeId, portId);
}

From source file:com.atwelm.aezwidget.responses.openhab.OpenHABFetchLayoutResponse.java

License:Apache License

public static List<OpenHABWidget> parseWidgets(JsonElement widget, Gson gson) {
    List<OpenHABWidget> widgets = new LinkedList<OpenHABWidget>();

    if (widget != null) {
        if (widget.isJsonObject()) {
            OpenHABWidget innerWidget = gson.fromJson(widget, OpenHABWidget.class);
            widgets.add(innerWidget);//from   w  ww.  jav  a 2s.c  om
        } else if (widget.isJsonArray()) {
            JsonArray array = widget.getAsJsonArray();

            for (JsonElement element : array) {
                if (element.isJsonObject()) {
                    OpenHABWidget innerWidget = gson.fromJson(element, OpenHABWidget.class);
                    widgets.add(innerWidget);
                } else {
                    // Log error
                }
            }
        }
    }
    return widgets;
}

From source file:com.azure.webapi.JsonEntityParser.java

License:Open Source License

/**
 * Parses the JSON object to a typed list
 * /*  w w w. ja v  a  2s  .c  om*/
 * @param results
 *            JSON results
 * @param gson
 *            Gson object used for parsing
 * @param clazz
 *            Target entity class
 * @return List of entities
 */
public static <E> List<E> parseResults(JsonElement results, Gson gson, Class<E> clazz) {
    List<E> result = new ArrayList<E>();
    String idPropertyName = getIdPropertyName(clazz);

    // Parse results
    if (results.isJsonArray()) // Query result
    {
        JsonArray elements = results.getAsJsonArray();

        for (JsonElement element : elements) {
            changeIdPropertyName(element.getAsJsonObject(), idPropertyName);
            E typedElement = gson.fromJson(element, clazz);
            result.add(typedElement);
        }
    } else { // Lookup result
        if (results.isJsonObject()) {
            changeIdPropertyName(results.getAsJsonObject(), idPropertyName);
        }
        E typedElement = gson.fromJson(results, clazz);
        result.add(typedElement);
    }
    return result;
}

From source file:com.azure.webapi.MobileServiceJsonTable.java

License:Open Source License

/**
 * Looks up a row in the table and retrieves its JSON value.
 * /*from  w w w . j  a va2  s  . c o m*/
 * @param id
 *            The id of the row
 * @param parameters           
 *            A list of user-defined parameters and values to include in the request URI query string
 * @param callback
 *            Callback to invoke after the operation is completed
 */
public void lookUp(Object id, List<Pair<String, String>> parameters,
        final TableJsonOperationCallback callback) {
    // Create request URL   
    String url;
    try {
        Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon();
        uriBuilder.path(TABLES_URL);
        uriBuilder.appendPath(URLEncoder.encode(mTableName, MobileServiceClient.UTF8_ENCODING));
        uriBuilder.appendPath(URLEncoder.encode(id.toString(), MobileServiceClient.UTF8_ENCODING));

        if (parameters != null && parameters.size() > 0) {
            for (Pair<String, String> parameter : parameters) {
                uriBuilder.appendQueryParameter(parameter.first, parameter.second);
            }
        }
        url = uriBuilder.build().toString();
    } catch (UnsupportedEncodingException e) {
        if (callback != null) {
            callback.onCompleted(null, e, null);
        }
        return;
    }

    executeGetRecords(url, new TableJsonQueryCallback() {

        @Override
        public void onCompleted(JsonElement results, int count, Exception exception,
                ServiceFilterResponse response) {
            if (callback != null) {
                if (exception == null && results != null) {
                    if (results.isJsonArray()) { // empty result
                        callback.onCompleted(null,
                                new MobileServiceException("A record with the specified Id cannot be found"),
                                response);
                    } else { // Lookup result
                        callback.onCompleted(results.getAsJsonObject(), exception, response);
                    }
                } else {
                    callback.onCompleted(null, exception, response);
                }
            }
        }
    });
}

From source file:com.baidu.cc.configuration.service.impl.VersionServiceImpl.java

License:Apache License

/**
 * ??./*w w w .j ava 2 s. c  om*/
 * 
 * @param file
 *            
 * @param versionId
 *            the version id
 * @throws IOException
 *             ?
 */
@Override
public void importFromFile(File file, Long versionId) throws IOException {
    byte[] byteArray = FileUtils.readFileToByteArray(file);

    Hex encoder = new Hex();
    try {
        byteArray = encoder.decode(byteArray);
    } catch (DecoderException e) {
        throw new IOException(e.getMessage());
    }
    String json = new String(byteArray, SysUtils.UTF_8);

    // parse from gson
    JsonParser jsonParser = new JsonParser();
    JsonElement je = jsonParser.parse(json);

    if (!je.isJsonArray()) {
        throw new RuntimeException("illegal json string. must be json array.");
    }

    JsonArray jsonArray = je.getAsJsonArray();

    int size = jsonArray.size();
    Version version = new Version();
    List<ConfigGroup> groups = new ArrayList<ConfigGroup>();
    ConfigGroup group;
    List<ConfigItem> items;
    ConfigItem item;

    for (int i = 0; i < size; i++) {
        JsonObject jo = jsonArray.get(i).getAsJsonObject();
        group = gson.fromJson(jo, ConfigGroup.class);

        // get sub configuration item
        JsonArray subItemsJson = jo.get(CONFIG_ITEMS_ELE).getAsJsonArray();

        int subSize = subItemsJson.size();
        items = new ArrayList<ConfigItem>();
        for (int j = 0; j < subSize; j++) {
            item = gson.fromJson(subItemsJson.get(j), ConfigItem.class);
            items.add(item);
        }

        group.setConfigItems(items);
        groups.add(group);
    }

    version.setConfigGroups(groups);
    configCopyService.copyConfigItemsFromVersion(version, versionId);
}

From source file:com.balajeetm.mystique.core.JsonMystique.java

License:Open Source License

/**
 * Gets the fields.//from  w  w  w  .j  ava  2 s. c  o m
 *
 * @param source the source
 * @param dependencies the dependencies
 * @param aces the aces
 * @param path the path
 * @param fields the fields
 * @return the fields
 */
private Boolean getFields(JsonElement source, JsonObject dependencies, JsonObject aces, JsonArray path,
        List<JsonElement> fields) {
    Boolean isLoopy = Boolean.FALSE;
    if (null != path) {
        if (path.size() > 0) {
            for (JsonElement jsonElement : path) {
                if (jsonElement.isJsonArray()) {
                    JsonArray fromArray = jsonElement.getAsJsonArray();
                    isLoopy = isLoopy || jsonLever.updateFields(source, dependencies, aces, fields, fromArray);
                    // Once isloopy, the loop doesn't execute anymore
                } else {
                    isLoopy = isLoopy || jsonLever.updateFields(source, dependencies, aces, fields, path);
                    break;
                }
            }
        } else {
            isLoopy = isLoopy || jsonLever.updateFields(source, dependencies, aces, fields, path);
        }
    }
    return isLoopy;
}