Example usage for com.google.gson JsonObject get

List of usage examples for com.google.gson JsonObject get

Introduction

In this page you can find the example usage for com.google.gson JsonObject get.

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:augsburg.se.alltagsguide.common.EventCategory.java

License:Open Source License

@Nullable
public static EventCategory fromJson(@NonNull final JsonObject jsonCategory) {
    if (jsonCategory.isJsonNull()) {
        return null;
    }//ww  w  .  j  av  a 2  s.  co m
    JsonElement idElement = jsonCategory.get("id");
    if (idElement.isJsonNull()) {
        return null;
    }
    int id = Helper.getIntOrDefault(idElement, -1);
    if (id == -1) {
        return null;
    }
    String name = jsonCategory.get("name").getAsString();
    int parent = jsonCategory.get("parent").getAsInt();
    return new EventCategory(id, name, parent);
}

From source file:augsburg.se.alltagsguide.common.EventLocation.java

License:Open Source License

@Nullable
public static EventLocation fromJson(@NonNull JsonObject jsonPage) {
    if (jsonPage.isJsonNull()) {
        return null;
    }//from  www  . j  a va  2  s.  c o m
    JsonElement idElement = jsonPage.get("id");
    if (idElement.isJsonNull()) {
        return null;
    }
    int id = Helper.getIntOrDefault(idElement, -1);
    if (id == -1) {
        return null;
    }
    return new EventLocation(id, Helper.getStringOrDefault(jsonPage.get("name"), null),
            Helper.getStringOrDefault(jsonPage.get("address"), null),
            Helper.getStringOrDefault(jsonPage.get("town"), null),
            Helper.getStringOrDefault(jsonPage.get("state"), null),
            Helper.getIntOrDefault(jsonPage.get("postcode"), 0),
            Helper.getStringOrDefault(jsonPage.get("region"), null),
            Helper.getStringOrDefault(jsonPage.get("country"), null),
            Helper.getFloatOrDefault(jsonPage.get("latitude"), 0.0f),
            Helper.getFloatOrDefault(jsonPage.get("longitude"), 0.0f));
}

From source file:augsburg.se.alltagsguide.common.EventPage.java

License:Open Source License

@NonNull
public static EventPage fromJson(@NonNull final JsonObject jsonPage) {
    Page page = Page.fromJson(jsonPage);
    //TODO jsonPage.get("page") !?
    Event event = Event.fromJson(jsonPage.get("event").getAsJsonObject(), page.getId());
    JsonElement locationElement = jsonPage.get("location");
    EventLocation location = null;//from  w  w  w . j a  v  a  2s . c o m
    if (locationElement != null && !locationElement.isJsonNull()) {
        location = EventLocation.fromJson(locationElement.getAsJsonObject());
    }
    List<EventTag> tags = EventTag.fromJson(jsonPage.get("tags").getAsJsonArray());
    List<EventCategory> categories = EventCategory.fromJson(jsonPage.get("categories").getAsJsonArray());
    return new EventPage(page, event, location, tags, categories);
}

From source file:augsburg.se.alltagsguide.common.EventTag.java

License:Open Source License

@NonNull
public static EventTag fromJson(@NonNull final JsonObject jsonTag) {
    String name = Helper.getStringOrDefault(jsonTag.get("name"), "");
    //TODO Tags have an id now.
    return new EventTag(name);
}

From source file:augsburg.se.alltagsguide.common.Language.java

License:Open Source License

@NonNull
public static Language fromJson(JsonObject jsonPage) {
    int id = jsonPage.get("id").getAsInt();
    String shortName = jsonPage.get("code").getAsString();
    String nativeName = jsonPage.get("native_name").getAsString();
    String countryFlagUrl = jsonPage.get("country_flag_url").getAsString();
    return new Language(id, shortName, nativeName, countryFlagUrl);
}

From source file:augsburg.se.alltagsguide.common.Location.java

License:Open Source License

@NonNull
public static Location fromJson(JsonObject jsonPage) {
    int id = jsonPage.get("id").getAsInt();
    String name = jsonPage.get("name").getAsString();
    String icon = jsonPage.get("icon").isJsonNull() ? null : jsonPage.get("icon").getAsString();
    String path = jsonPage.get("path").getAsString();
    String description = jsonPage.get("description").getAsString();
    boolean global = false;
    if (jsonPage.has("global")) {
        global = !jsonPage.get("global").isJsonNull() && jsonPage.get("global").getAsBoolean();
    }//from  w  ww.ja v  a2  s.  c  om
    int color = jsonPage.get("color").isJsonNull() ? Color.parseColor("#00BCD4")
            : Color.parseColor(jsonPage.get("color").getAsString());
    String cityImage = jsonPage.get("cover_image").isJsonNull() ? ""
            : jsonPage.get("cover_image").getAsString();
    if (cityImage == null || "".equals(cityImage)) {
        cityImage = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Brandenburger_Tor_abends.jpg/300px-Brandenburger_Tor_abends.jpg";
    }
    float latitude = 0.0f; //TODO
    float longitude = 0.0f; //TODO
    boolean debug = false;
    if (jsonPage.has("live")) {
        JsonElement elem = jsonPage.get("live");
        if (elem != null && !elem.isJsonNull()) {
            debug = elem.getAsBoolean();
        }
    }
    return new Location(id, name, icon, path, description, global, color, cityImage, latitude, longitude,
            debug);
}

From source file:augsburg.se.alltagsguide.common.Page.java

License:Open Source License

@NonNull
public static Page fromJson(@NonNull final JsonObject jsonPage) {
    int id = jsonPage.get("id").getAsInt();
    String title = jsonPage.get("title").getAsString();
    String type = jsonPage.get("type").getAsString();
    String status = jsonPage.get("status").getAsString();
    long modified;
    try {//from  w w w  .j  a v  a2s.c o  m
        modified = Helper.FROM_DATE_FORMAT.parse(jsonPage.get("modified_gmt").getAsString()).getTime();
    } catch (ParseException e) {
        Ln.e(e);
        modified = -1;
    }
    String description = jsonPage.get("excerpt").getAsString();
    String content = jsonPage.get("content").getAsString();
    int parentId = jsonPage.get("parent").getAsInt();
    int order = jsonPage.get("order").getAsInt();
    String thumbnail = jsonPage.get("thumbnail").isJsonNull() ? "" : jsonPage.get("thumbnail").getAsString();
    Author author = Author.fromJson(jsonPage.get("author").getAsJsonObject());
    List<AvailableLanguage> languages = AvailableLanguage.fromJson(jsonPage.get("available_languages"));

    boolean autoTranslated = false;
    if (jsonPage.has("automatic_translation")) {
        JsonElement elem = jsonPage.get("automatic_translation");
        if (elem != null && !elem.isJsonNull()) {
            autoTranslated = elem.getAsBoolean();
        }
    }
    return new Page(id, title, type, status, modified, description, content, parentId, order, thumbnail, author,
            autoTranslated, languages);
}

From source file:augsburg.se.alltagsguide.serialization.EventPageSerializer.java

License:Open Source License

@NonNull
private List<EventPage> getPagesByParentId(final EventPage parent, final int parentId,
        @NonNull final JsonArray jsonPages) {
    final List<EventPage> result = new ArrayList<>();
    for (int i = 0; i < jsonPages.size(); i++) {
        JsonObject jsonPage = jsonPages.get(i).getAsJsonObject();
        if (jsonPage.get("parent").getAsInt() == parentId) {
            EventPage page = EventPage.fromJson(jsonPage);
            page.setParent(parent);/*  w w w  . j a  v  a  2  s .c  o m*/
            result.add(page);
        }
    }
    return result;
}

From source file:authorization.AuthAPIService.java

License:Open Source License

public AuthorizationResult sendPermissionRequest(boolean isWrite, String body, String subjectInfo,
        boolean isCertificate) {
    HttpURLConnection connection = null;
    try {/*from  w w w.jav a 2s.c  o  m*/
        //Create connection
        String writeURL = isWrite ? "true" : "false";
        String finalURL = authServiceURI + "?ac=true&write=" + writeURL;
        logger.debug("Sending request. URI:" + finalURL);
        URL url = new URL(finalURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        if (!isCertificate)
            connection.setRequestProperty("Cookie", subjectInfo);

        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.connect();

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(body);
        wr.close();

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
        }
        rd.close();

        logger.debug("RESPONSE:" + response.toString());

        if (response.toString().equals("false")) {
            return new Unauthorized(new UserInfo(UserInfo.apply$default$1(), UserInfo.apply$default$2()));
        } else if (response.toString().equals("true")) {
            return new Authorized(new UserInfo(UserInfo.apply$default$1(), UserInfo.apply$default$2()));
        }

        JsonObject responseObject = new JsonParser().parse(response.toString()).getAsJsonObject();//response.toString(); //reuse variable
        String isAuthenticated = responseObject.get("result").getAsString();
        String userName = responseObject.get("userID").getAsString();
        return isAuthenticated.equalsIgnoreCase("ok")
                ? new Authorized(new UserInfo(UserInfo.apply$default$1(), scala.Option.apply(userName)))
                : new Unauthorized(new UserInfo(UserInfo.apply$default$1(), scala.Option.apply(userName)));
    } catch (Exception e) {
        logger.error("During http request", e);
        return new Unauthorized(new UserInfo(UserInfo.apply$default$1(), UserInfo.apply$default$2()));
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

License:MIT License

/**
 * Deserializes a fancy message from its JSON representation. This JSON
 * representation is of the format of that returned by
 * {@link #toJSONString()}, and is compatible with vanilla inputs.
 *
 * @param json The JSON string which represents a fancy message.
 * @return A {@code MessageUtil} representing the parameterized JSON
 * message.//from   www . ja v a 2 s.  c  o  m
 */
public static MessageUtil deserialize(String json) {
    JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
    JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
    MessageUtil returnVal = new MessageUtil();
    returnVal.messageParts.clear();
    for (JsonElement mPrt : extra) {
        MessagePart component = new MessagePart();
        JsonObject messagePart = mPrt.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
            // Deserialize text
            if (TextualComponent.isTextKey(entry.getKey())) {
                // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
                Map<String, Object> serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance
                serializedMapForm.put("key", entry.getKey());
                if (entry.getValue().isJsonPrimitive()) {
                    // Assume string
                    serializedMapForm.put("value", entry.getValue().getAsString());
                } else {
                    // Composite object, but we assume each element is a string
                    for (Map.Entry<String, JsonElement> compositeNestedElement : entry.getValue()
                            .getAsJsonObject().entrySet()) {
                        serializedMapForm.put("value." + compositeNestedElement.getKey(),
                                compositeNestedElement.getValue().getAsString());
                    }
                }
                component.text = TextualComponent.deserialize(serializedMapForm);
            } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
                if (entry.getValue().getAsBoolean()) {
                    component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
                }
            } else if (entry.getKey().equals("color")) {
                component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
            } else if (entry.getKey().equals("clickEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.clickActionName = object.get("action").getAsString();
                component.clickActionData = object.get("value").getAsString();
            } else if (entry.getKey().equals("hoverEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.hoverActionName = object.get("action").getAsString();
                if (object.get("value").isJsonPrimitive()) {
                    // Assume string
                    component.hoverActionData = new JsonString(object.get("value").getAsString());
                } else {
                    // Assume composite type
                    // The only composite type we currently store is another MessageUtil
                    // Therefore, recursion time!
                    component.hoverActionData = deserialize(object.get("value")
                            .toString() /* This should properly serialize the JSON object as a JSON string */);
                }
            } else if (entry.getKey().equals("insertion")) {
                component.insertionData = entry.getValue().getAsString();
            } else if (entry.getKey().equals("with")) {
                for (JsonElement object : entry.getValue().getAsJsonArray()) {
                    if (object.isJsonPrimitive()) {
                        component.translationReplacements.add(new JsonString(object.getAsString()));
                    } else {
                        // Only composite type stored in this array is - again - MessageUtils
                        // Recurse within this function to parse this as a translation replacement
                        component.translationReplacements.add(deserialize(object.toString()));
                    }
                }
            }
        }
        returnVal.messageParts.add(component);
    }
    return returnVal;
}