Example usage for com.google.gson JsonElement isJsonObject

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

Introduction

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

Prototype

public boolean isJsonObject() 

Source Link

Document

provides check for verifying if this element is a Json object or not.

Usage

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

@SuppressWarnings("WeakerAccess")
public T deserialize(String id, JsonElement json, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("expected a json object to parse into " + klass + " but received " + json);
    }//from  w w  w.  java 2 s  . c  o m
    T t = null;
    try {
        JsonObject jsonObject = json.getAsJsonObject();
        t = parseObject(context, id, jsonObject);
        parseRelationships(context, t, jsonObject);
        parseLinks(context, t, jsonObject);
    } catch (IllegalAccessException e) {
        throw new JsonParseException("Cannot set ID/link on " + t, e);
    } catch (InvocationTargetException e) {
        throw new JsonParseException("Cannot set ID/link on " + t, e);
    } catch (InstantiationException e) {
        throw new JsonParseException(
                "Cannot create an instance of " + klass + ". Make sure it has a no-arg" + " constructor", e);
    }
    return t;
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

private void parseLinks(JsonDeserializationContext context, T t, JsonObject jsonObject)
        throws IllegalAccessException, InvocationTargetException {
    JsonElement links = jsonObject.get("links");
    if (links != null && links.isJsonObject()) {
        JsonObject linksObject = links.getAsJsonObject();
        Setter linksObjectSetter = linkSetters.get("");
        if (linksObjectSetter != null) {
            linksObjectSetter.setOnObject(t, context.deserialize(links, JsonApiLinks.class));
        }//from w  w w.ja  v  a  2 s. co m
        for (Map.Entry<String, Setter> entry : linkSetters.entrySet()) {
            JsonElement link = linksObject.get(entry.getKey());
            if (link != null && link.isJsonPrimitive()) {
                entry.getValue().setOnObject(t, link.getAsString());
            }
        }
    }
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

private void parseRelationships(JsonDeserializationContext context, T t, JsonObject jsonObject)
        throws IllegalAccessException, InvocationTargetException {
    JsonElement relationships = jsonObject.get("relationships");
    if (relationships != null && relationships.isJsonObject()) {
        JsonObject relationshipsObject = relationships.getAsJsonObject();
        for (Map.Entry<String, Setter> entry : relationshipSetters.entrySet()) {
            JsonElement relationship = relationshipsObject.get(entry.getKey());
            if (relationship != null && relationship.isJsonObject()) {
                if (entry.getValue().type() == JsonApiRelationshipList.class) {
                    entry.getValue().setOnObject(t,
                            context.deserialize(relationship, JsonApiRelationshipList.class));
                } else if (entry.getValue().type() == JsonApiRelationship.class) { // JsonApiRelationship
                    entry.getValue().setOnObject(t,
                            context.deserialize(relationship, JsonApiRelationship.class));
                } else { // String list or id
                    JsonElement data = relationship.getAsJsonObject().get("data");
                    if (data != null) {
                        if (data.isJsonObject()) {
                            JsonElement relationshipIdElement = data.getAsJsonObject().get("id");
                            if (relationshipIdElement != null) {
                                if (relationshipIdElement.isJsonPrimitive()) {
                                    entry.getValue().setOnObject(t, relationshipIdElement.getAsString());
                                }//from   w  w w.  j a  v  a2 s.  co  m
                            }
                        } else if (data.isJsonArray()) {
                            List<String> idList = parseIds(data.getAsJsonArray());
                            entry.getValue().setOnObject(t, idList);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

private T parseObject(JsonDeserializationContext context, String id, JsonObject jsonObject)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    JsonElement attributesElement = jsonObject.get("attributes");
    T object;/* w  w  w.  j a  v a2 s. co  m*/
    if (attributesElement != null && attributesElement.isJsonObject()) {
        object = context.deserialize(attributesElement, klass);
    } else {
        object = klass.newInstance();
    }
    idSetter.setOnObject(object, id);
    return object;
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

private List<String> parseIds(JsonArray jsonArray) {
    List<String> result = new ArrayList<String>(jsonArray.size());
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement item = jsonArray.get(i);
        if (item.isJsonObject()) {
            JsonElement idField = item.getAsJsonObject().get("id");
            if (idField != null && idField.isJsonPrimitive()) {
                result.add(idField.getAsString());
            }//from  www.  j a v  a  2 s. c om
        }
    }
    return result;
}

From source file:com.blackducksoftware.integration.hub.detect.detector.packagist.PackagistParser.java

License:Apache License

private List<NameVersion> parseDependencies(final JsonObject packageJson, final boolean checkDev) {
    final List<NameVersion> dependencies = new ArrayList<>();

    final JsonElement require = packageJson.get("require");
    if (require != null && require.isJsonObject()) {
        dependencies.addAll(parseDependenciesFromRequire(require.getAsJsonObject()));
    }/*from   w  w  w  .  j  av  a2 s. com*/

    if (checkDev) {
        final JsonElement devRequire = packageJson.get("require-dev");
        if (devRequire != null && devRequire.isJsonObject()) {
            dependencies.addAll(parseDependenciesFromRequire(devRequire.getAsJsonObject()));
        }

    }

    return dependencies;
}

From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java

License:Open Source License

/**
 * Creates a text component given its JSON representation. Both the shorthand notation as
 * a raw string as well as the notation as a full-blown JSON object are supported.
 *
 * @param json The JSON element to be deserialized into a text component
 *
 * @return The deserialized TextComponent
 *///from  w  w w . j a  va  2s  .  c o m
private TextComponent deserializeTextComponent(JsonElement json) {
    final TextComponent component = new TextComponent("");

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            component.setText(primitive.getAsString());
        }
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();

        if (object.has("text")) {
            JsonElement textElement = object.get("text");
            if (textElement.isJsonPrimitive()) {
                JsonPrimitive textPrimitive = textElement.getAsJsonPrimitive();
                if (textPrimitive.isString()) {
                    component.setText(textPrimitive.getAsString());
                }
            }
        }

        if (object.has("extra")) {
            JsonElement extraElement = object.get("extra");
            if (extraElement.isJsonArray()) {
                JsonArray extraArray = extraElement.getAsJsonArray();
                for (int i = 0; i < extraArray.size(); ++i) {
                    JsonElement fieldElement = extraArray.get(i);
                    component.addChild(this.deserializeComponent(fieldElement));
                }
            }
        }
    }

    return component;
}

From source file:com.builtbroken.builder.html.data.ImageData.java

/**
 * Loads a file from disk as a json file
 * then parses the file looking for an array
 * of links formatted as {"key":{"text":"String","url":"String"}}
 *
 * @param file - file to load, throws an exception if the file is invalid
 *//*from   ww w  .ja  v  a2  s .  c o  m*/
public void loadDataFromFile(File file) {
    if (file.exists()) {
        if (file.isFile()) {
            JsonElement linkJson = Utils.toJsonElement(file);
            if (linkJson.isJsonObject()) {
                parseJsonImageArray(linkJson.getAsJsonObject());
            } else {
                throw new IllegalArgumentException("Link data file is not a valid json object. File = " + file);
            }
        } else {
            throw new IllegalArgumentException("Link data file is not a valid file. File = " + file);
        }
    } else {
        throw new IllegalArgumentException("Link data file is missing. File = " + file);
    }
}

From source file:com.builtbroken.builder.html.data.LinkData.java

/**
 * Loads a file from disk as a json file
 * then parses the file looking for an array
 * of links formatted as {"key":{"text":"String","url":"String"}}
 *
 * @param file - file to load, throws an exception if the file is invalid
 *///from  w  ww  . j  a  va 2 s .c  om
public void loadDataFromFile(File file) {
    if (file.exists()) {
        if (file.isFile()) {
            JsonElement linkJson = Utils.toJsonElement(file);
            if (linkJson.isJsonObject()) {
                parseJsonLinkArray(linkJson.getAsJsonObject());
            } else {
                throw new IllegalArgumentException("Link data file is not a valid json object. File = " + file);
            }
        } else {
            throw new IllegalArgumentException("Link data file is not a valid file. File = " + file);
        }
    } else {
        throw new IllegalArgumentException("Link data file is missing. File = " + file);
    }
}

From source file:com.builtbroken.builder.html.page.PageData.java

/**
 * Called to load the page from json//from  ww w.  j  a  v  a2  s  . c  o m
 */
public void load(PageBuilder builder) {
    imgReplaceKeys = new HashMap();
    linkReplaceKeys = new HashMap();
    //TODO format nano time outputs on debugger
    debug("Loading new Page Data");

    long startTime = System.nanoTime();
    debug("\tLoading file from disk");
    JsonElement element = Utils.toJsonElement(file);
    startTime = System.nanoTime() - startTime;
    debug("\tDone..." + startTime + "ns");

    if (element.isJsonObject()) {
        debug("\tParsing json");
        startTime = System.nanoTime();

        JsonObject object = element.getAsJsonObject();
        if (object.has("pageName")) {
            pageName = object.getAsJsonPrimitive("pageName").getAsString();
            debug("\tDisplay Name: " + pageName);
        }
        if (object.has("fileName")) {
            fileNameOverride = object.getAsJsonPrimitive("fileName").getAsString();
            debug("\tFile Name: " + fileNameOverride);
        }
        if (object.has("fileExtension")) {
            fileExtension = object.getAsJsonPrimitive("fileExtension").getAsString();
            debug("\tFile Extension: " + fileExtension);
        }
        if (object.has("type")) {
            type = object.getAsJsonPrimitive("type").getAsString().toLowerCase();
            debug("\tType: " + type);
            if (type.equalsIgnoreCase("ignore")) {
                return;
            }
        }
        if (object.has("category_display_name")) {
            categoryDisplayName = object.getAsJsonPrimitive("category_display_name").getAsString();
            debug("\tCategory Display Name: " + type);
        }
        if (object.has("category_display_order")) {
            categoryDisplayOrder = object.getAsJsonPrimitive("category_display_order").getAsString();
            debug("\tCategory Display Order: " + type);
        }
        if (object.has("category")) {
            category = object.getAsJsonPrimitive("category").getAsString().toLowerCase();
            debug("\tCategory: " + category);
        }
        if (object.has("replaceKeys")) {
            Gson gson = new Gson();
            Map<String, String> map = new HashMap();
            map = (Map<String, String>) gson.fromJson(object.get("replaceKeys"), map.getClass());
            linkReplaceKeys.putAll(map);
            debug("\tLinks Keys: " + linkReplaceKeys.size());
        }
        if (object.has("imageKeys")) {
            Gson gson = new Gson();
            Map<String, String> map = new HashMap();
            map = (Map<String, String>) gson.fromJson(object.get("imageKeys"), map.getClass());
            imgReplaceKeys.putAll(map);
            debug("\tImage Keys: " + imgReplaceKeys.size());
        }
        if (object.has("content")) {
            debug("\tLoading Page Content");
            long time = System.nanoTime();
            //Split HTML into segments for injection
            process(toHTML(object.getAsJsonObject("content")));
            time = System.nanoTime() - time;
            debug("\tDone..." + time + "ns");
        }

    } else {
        throw new RuntimeException(
                "File " + file + " is not a valid json object so can not be parsed into a wiki page.");
    }

    debug("\tProcessing reference data...");
    //Loop all contained link replace keys
    for (Map.Entry<String, String> entry : linkReplaceKeys.entrySet()) {
        final String key = entry.getKey().toLowerCase();
        if (!builder.linkData.linkReplaceKeys.containsKey(key)) {
            String html = "<a href=\"" + getOutput(builder.vars.get("outputPath")) + "\">" + entry.getValue()
                    + "</a>";
            builder.linkData.linkReplaceKeys.put(key, html);
            debug("\t\tKey: " + key + " --> " + html);
        } else {
            throw new RuntimeException("Duplicate link key[" + entry.getKey() + "] was found for page ["
                    + pageName + "] key is linked to " + builder.linkData.linkReplaceKeys.get(key));
        }
    }
    //Loop all image replace keys
    for (Map.Entry<String, String> entry : imgReplaceKeys.entrySet()) {
        final String key = entry.getKey().toLowerCase();
        if (!builder.imageData.imageReplaceKeys.containsKey(key)) {
            String path = builder.vars.get("imagePath") + entry.getValue();
            String html = "<img src=\"" + entry.getValue() + "\">";
            builder.imageData.imageReplaceKeys.put(key, html);
            builder.imageData.images.put(key, path);
            debug("\t\tKey: " + key + " --> " + html);
        } else {
            throw new RuntimeException("Duplicate image key[" + entry.getKey() + "] was found for page ["
                    + pageName + "] key is linked to " + builder.imageData.imageReplaceKeys.get(key));
        }
    }

    //Debug
    startTime = System.nanoTime() - startTime;
    debug("Done..." + startTime + "ns");
}