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.nextdoor.bender.operation.json.key.KeyNameOperation.java

License:Apache License

protected void perform(JsonObject obj) {
    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {

        JsonElement val = entry.getValue();
        obj.remove(entry.getKey());//from   w w  w.j  a  v a  2  s .c  om
        String key = entry.getKey().toLowerCase().replaceAll("[ .]", "_");

        if (val.isJsonPrimitive()) {
            JsonPrimitive prim = val.getAsJsonPrimitive();

            if (prim.isBoolean()) {
                obj.add(key + "__bool", val);
            } else if (prim.isNumber()) {
                if (prim.toString().contains(".")) {
                    obj.add(key + "__float", val);
                } else {
                    obj.add(key + "__long", val);
                }
            } else if (prim.isString()) {
                obj.add(key + "__str", val);
            }
        } else if (val.isJsonObject()) {
            obj.add(key, val);
            perform(val.getAsJsonObject());
        } else if (val.isJsonArray()) {
            obj.add(key + "__arr", val);
        }
    }
}

From source file:com.nextdoor.bender.operation.json.key.KeyNameReplacementOperation.java

License:Apache License

protected void performOnArray(JsonElement elm) {
    if (elm.isJsonObject()) {
        perform(elm.getAsJsonObject());// w ww  .j  a  v  a  2  s . co m
    } else if (elm.isJsonArray()) {
        JsonArray arr = elm.getAsJsonArray();
        arr.forEach(item -> {
            performOnArray(item);
        });
    }
}

From source file:com.nextdoor.bender.operation.json.key.KeyNameReplacementOperation.java

License:Apache License

protected void perform(JsonObject obj) {
    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {
        JsonElement val = entry.getValue();

        /*// w  ww . ja v  a 2 s .  c  o m
         * See if key matches. If it does then drop or rename. Otherwise keep recursing.
         */
        Matcher m = this.pattern.matcher(entry.getKey());
        boolean found = m.find();
        if (found) {
            /*
             * If instructed to drop then remove and continue. Otherwise remove and later rename;
             */
            obj.remove(entry.getKey());
            if (this.drop) {
                continue;
            }

            /*
             * Rename
             */
            if (val.isJsonPrimitive()) {
                obj.add(m.replaceAll(this.replacement), val);
            } else if (val.isJsonObject()) {
                obj.add(m.replaceAll(this.replacement), val);
                perform(val.getAsJsonObject());
            } else if (val.isJsonArray()) {
                JsonArray arr = val.getAsJsonArray();

                arr.forEach(item -> {
                    performOnArray(item);
                });
                obj.add(m.replaceAll(this.replacement), val);
            }
            continue;
        }

        /*
         * Keep recursing
         */
        if (val.isJsonObject()) {
            perform(val.getAsJsonObject());
        } else if (val.isJsonArray()) {
            JsonArray arr = val.getAsJsonArray();
            arr.forEach(item -> {
                performOnArray(item);
            });
        }

    }
}

From source file:com.nextdoor.bender.operation.json.key.LowerCaseKeyOperation.java

License:Apache License

protected void perform(JsonObject obj) {
    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {

        JsonElement val = entry.getValue();
        obj.remove(entry.getKey());/*from  w  w w  .  j  a  v a  2s.  c  om*/
        String key = entry.getKey().toLowerCase();

        if (val.isJsonPrimitive()) {
            obj.add(key, val);
        } else if (val.isJsonObject()) {
            obj.add(key, val);
            perform(val.getAsJsonObject());
        } else if (val.isJsonArray()) {
            obj.add(key, val);

            val.getAsJsonArray().forEach(elm -> {
                if (elm.isJsonObject()) {
                    perform((JsonObject) elm);
                }
            });
        }
    }
}

From source file:com.nextdoor.bender.operation.json.value.DropArraysOperation.java

License:Apache License

protected void perform(JsonObject obj) {
    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {
        JsonElement val = entry.getValue();

        if (val.isJsonArray()) {
            obj.remove(entry.getKey());// w ww  .j  a v a 2s. com
        } else if (val.isJsonObject()) {
            perform(val.getAsJsonObject());
        }
    }
}

From source file:com.optimizely.ab.config.parser.AudienceGsonDeserializer.java

License:Apache License

@Override
public Audience deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = json.getAsJsonObject();

    String id = jsonObject.get("id").getAsString();
    String name = jsonObject.get("name").getAsString();

    JsonElement conditionsElement = jsonObject.get("conditions");
    if (!typeOfT.toString().contains("TypedAudience")) {
        conditionsElement = parser.parse(jsonObject.get("conditions").getAsString());
    }//from  w w w.j  av a2 s. c o m
    Condition conditions = null;
    if (conditionsElement.isJsonArray()) {
        List<Object> rawObjectList = gson.fromJson(conditionsElement, List.class);
        conditions = ConditionUtils.parseConditions(UserAttribute.class, rawObjectList);
    } else if (conditionsElement.isJsonObject()) {
        Object object = gson.fromJson(conditionsElement, Object.class);
        conditions = ConditionUtils.parseConditions(UserAttribute.class, object);
    }

    return new Audience(id, name, conditions);
}

From source file:com.optimizely.ab.config.parser.GsonHelpers.java

License:Apache License

static Condition parseAudienceConditions(JsonObject experimentJson) {

    if (!experimentJson.has("audienceConditions"))
        return null;

    Gson gson = new Gson();

    JsonElement conditionsElement = experimentJson.get("audienceConditions");

    if (conditionsElement.isJsonArray()) {
        List<Object> rawObjectList = gson.fromJson(conditionsElement, List.class);
        return ConditionUtils.<AudienceIdCondition>parseConditions(AudienceIdCondition.class, rawObjectList);
    } else {//  w  ww  . j  av  a2 s. c  om
        Object jsonObject = gson.fromJson(conditionsElement, Object.class);
        return ConditionUtils.<AudienceIdCondition>parseConditions(AudienceIdCondition.class, jsonObject);
    }

}

From source file:com.pearson.pdn.learningstudio.content.ContentService.java

License:Apache License

/**
 * Get links details from a specific item for a course with
 * Get /courses/{courseId}/items/{itemId}
 * using OAuth2 as a student, teacher or teaching assistant
 * /*from  w  w w .j a va  2 s  .c om*/
 * Example JSON structure: (Multimedia item)
 * 
 * { 
 *   "details": { 
 *     "access": {...}, 
 *     "schedule": {...}, 
 *     "self": {...},
 *     "selfType": "textMultimedias"
 *   }
 * }
 * 
 * @param courseId   ID of the course
 * @param itemId   ID of the item
 * @return   Response object with details of status and content
 * @throws IOException
 */
public Response getItemLinkDetails(String courseId, String itemId) throws IOException {
    Response response = getItem(courseId, itemId);
    if (response.isError()) {
        return response;
    }

    // should only be one item here, but it is returned in an array for some reason
    String courseItemsJson = response.getContent();
    JsonObject json = this.jsonParser.parse(courseItemsJson).getAsJsonObject();
    JsonArray items = json.get("items").getAsJsonArray();
    JsonObject detail = new JsonObject();

    // again, only one element expected here...
    Iterator<JsonElement> itemIterator = items.iterator();
    if (itemIterator.hasNext()) {
        JsonObject item = itemIterator.next().getAsJsonObject();
        JsonArray links = item.get("links").getAsJsonArray();

        for (Iterator<JsonElement> linkIter = links.iterator(); linkIter.hasNext();) {
            JsonObject link = linkIter.next().getAsJsonObject();
            String relativeUrl = this.getRelativePath(link.get("href").getAsString());

            response = doMethod(HttpMethod.GET, relativeUrl, NO_CONTENT);
            if (response.isError()) {
                return response;
            }

            JsonElement linkElement = this.jsonParser.parse(response.getContent());

            JsonElement title = link.get("title");
            // rel on link varies, so identify self by missing title
            if (title == null) {
                Map.Entry<String, JsonElement> self = linkElement.getAsJsonObject().entrySet().iterator()
                        .next();

                linkElement = self.getValue();
                // content items like to return a single resource in an array sometimes
                if (linkElement.isJsonArray()) {
                    linkElement = linkElement.getAsJsonArray().get(0);
                }

                detail.add("self", linkElement);
                detail.addProperty("selfType", self.getKey());
            } else {
                // remove the first layer wrapper. it's just repetitive
                linkElement = linkElement.getAsJsonObject().get(title.getAsString());
                detail.add(title.getAsString(), linkElement);
            }
        }

        JsonObject detailWrapper = new JsonObject();
        detailWrapper.add("details", detail);

        response.setContent(this.gson.toJson(detailWrapper));
    } else {
        // this should never happen, but it should be detected if it does
        throw new RuntimeException("Unexpected condition in library: No items");
    }

    return response;
}

From source file:com.podio.sdk.push.FayePushClient.java

License:Open Source License

private HashMap<String, ArrayList<Event>> parseEventData(String json) {
    HashMap<String, ArrayList<Event>> result = new HashMap<String, ArrayList<Event>>();

    if (Utils.isEmpty(json)) {
        return result;
    }/* ww w .  j  a v a  2s . c  o  m*/

    // Parse the root json element.
    JsonParser jsonParser = new JsonParser();
    JsonElement root = jsonParser.parse(json);
    JsonArray jsonElements;

    // Make sure we're always operating on an array of objects.
    if (root.isJsonArray()) {
        jsonElements = root.getAsJsonArray();
    } else if (root.isJsonObject()) {
        jsonElements = new JsonArray();
        jsonElements.add(root.getAsJsonObject());
    } else {
        return result;
    }

    JsonObject jsonObject;
    Gson gson = new Gson();

    // Search for all data bearing event objects.
    for (JsonElement jsonElement : jsonElements) {
        if (jsonElement.isJsonObject()) {
            jsonObject = jsonElement.getAsJsonObject();

            if (jsonObject.has("channel") && jsonObject.has("data")) {
                JsonObject fayeData = getJsonObject(jsonObject, "data");
                JsonObject podioData = getJsonObject(fayeData, "data");

                String key = getString(jsonObject, "channel");
                String type = getString(podioData, "event");

                if (Utils.notAnyEmpty(key, type)) {
                    try {
                        Event.Type eventType = Event.Type.valueOf(type);
                        Event event = gson.fromJson(podioData, eventType.getClassObject());

                        if (result.containsKey(key)) {
                            result.get(key).add(event);
                        } else {
                            ArrayList<Event> events = new ArrayList<Event>();
                            events.add(event);
                            result.put(key, events);
                        }
                    } catch (NullPointerException e) {
                        callbackManager.deliverError(e);
                    } catch (IllegalArgumentException e) {
                        callbackManager.deliverError(e);
                    } catch (JsonSyntaxException e) {
                        callbackManager.deliverError(e);
                    }
                }
            }
        }
    }

    return result;
}

From source file:com.podio.sdk.push.PushRequest.java

License:Open Source License

private static Status parseStatus(String json) {
    if (Utils.isEmpty(json)) {
        status = new Status(); // Defaults to "unknown error" status.
        return status;
    }/*from  w w w .j  a v  a2 s .  com*/

    // Parse the json string into an object tree.
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(json);
    JsonArray jsonArray;

    // Make a general data structure (a JsonArray) to search for the
    // first available status object (sometimes the API delivers the
    // Status object on its own, and sometimes in an array).
    if (jsonElement.isJsonArray()) {
        jsonArray = jsonElement.getAsJsonArray();
    } else {
        jsonArray = new JsonArray();
        jsonArray.add(jsonElement);
    }

    // Now try to find the first available Status JsonObject which
    // meets our minimum criteria.
    int size = jsonArray.size();

    for (int i = 0; i < size; i++) {
        jsonElement = jsonArray.get(i);

        if (jsonElement.isJsonObject()) {
            JsonObject jsonObject = jsonElement.getAsJsonObject();

            if (jsonObject.has("clientId") && jsonObject.has("channel") && jsonObject.has("successful")) {
                status = (new Gson()).fromJson(jsonObject, Status.class);

                if (status.hasAdvice()) {
                    advice = status.advice();
                }

                break;
            }
        }
    }

    return status;
}