Example usage for com.google.gson JsonObject entrySet

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

Introduction

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

Prototype

public Set<Map.Entry<String, JsonElement>> entrySet() 

Source Link

Document

Returns a set of members of this object.

Usage

From source file:com.frostwire.search.archiveorg.ArchiveorgSearchPerformer.java

License:Open Source License

private List<ArchiveorgFile> readFiles(String json) throws Exception {
    List<ArchiveorgFile> result = new LinkedList<>();

    JsonElement element = new JsonParser().parse(json);
    JsonObject obj = element.getAsJsonObject();
    JsonObject files = obj.getAsJsonObject("files");

    Iterator<Map.Entry<String, JsonElement>> it = files.entrySet().iterator();

    while (it.hasNext() && !isStopped()) {
        Map.Entry<String, JsonElement> e = it.next();
        String name = e.getKey();
        String value = e.getValue().toString();
        ArchiveorgFile file = JsonUtils.toObject(value, ArchiveorgFile.class);
        if (filter(file)) {
            file.filename = cleanName(name);
            result.add(file);//from  ww w.j a  v  a  2 s .com
        }
    }

    return result;
}

From source file:com.gamerking195.dev.lametric.RestfulWriter.java

License:Open Source License

private String getMojangApp() {
    Gson gson = new Gson();

    try {/*from   ww  w.  j a  va 2  s. co m*/
        String statusCheck;

        /*if (debug)
        statusCheck = "[{\"minecraft.net\":\"green\"},{\"session.minecraft.net\":\"green\"},{\"account.mojang.com\":\"green\"},{\"auth.mojang.com\":\"green\"},{\"skins.minecraft.net\":\"green\"},{\"authserver.mojang.com\":\"yellow\"},{\"sessionserver.mojang.com\":\"red\"},{\"api.mojang.com\":\"green\"},{\"textures.minecraft.net\":\"green\"},{\"mojang.com\":\"green\"}]";
        else*/

        statusCheck = readFrom("https://status.mojang.com/check");

        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> statuses = gson.fromJson(statusCheck, type);

        ArrayList<String> greenServices = new ArrayList<>();
        ArrayList<String> yellowServices = new ArrayList<>();
        ArrayList<String> redServices = new ArrayList<>();

        for (JsonObject object : statuses) {
            Set<Map.Entry<String, JsonElement>> entries = object.entrySet();
            for (Map.Entry<String, JsonElement> entry : entries) {
                if (entry.getKey().contains("skins"))
                    continue;

                if (debug)
                    System.out.println("SERVICE " + entry.getKey() + " IS "
                            + entry.getValue().getAsString().replace("\"", ""));

                switch (entry.getValue().getAsString().replace("\"", "")) {
                case "green":
                    greenServices.add(entry.getKey());
                    break;
                case "yellow":
                    yellowServices.add(entry.getKey());
                    break;
                case "red":
                    redServices.add(entry.getKey());
                    break;
                }
            }
        }

        if (yellowServices.size() == 0 && redServices.size() == 0) {
            FrameWrapper frames = new FrameWrapper(new ArrayList<>());
            frames.addFrame(mojangLaunch);
            frames.addFrame(new Frame("ALL SERVICES AVAILABLE", greenIcon));

            serviceDowntimeMap.clear();

            return gson.toJson(frames);
        } else {
            FrameWrapper frames = new FrameWrapper(new ArrayList<>());
            frames.addFrame(mojangLaunch);

            if (debug) {
                System.out.println("RED SERVICES SIZE = " + redServices.size());
                System.out.println("YELLOW SERVICES SIZE = " + yellowServices.size());
                System.out.println("GREEN SERVICES SIZE = " + greenServices.size());
            }

            for (String string : redServices) {
                if (serviceDowntimeMap.containsKey(string))
                    serviceDowntimeMap.put(string, serviceDowntimeMap.get(string) + 1);
                else
                    serviceDowntimeMap.put(string, 1);

                frames.addFrame(new Frame("SERVICE " + string.toUpperCase() + " UNAVAILABLE FOR "
                        + getTimeFancy(serviceDowntimeMap.get(string)), redIcon));
            }

            for (String string : yellowServices) {
                if (serviceDowntimeMap.containsKey(string))
                    serviceDowntimeMap.put(string, serviceDowntimeMap.get(string) + 1);
                else
                    serviceDowntimeMap.put(string, 1);

                String yellowIcon = "a3273";
                frames.addFrame(new Frame("SERVICE " + string.toUpperCase() + " UNSTABLE FOR "
                        + getTimeFancy(serviceDowntimeMap.get(string)), yellowIcon));
            }

            if (greenServices.size() > 0)
                frames.addFrame(new Frame("ALL OTHER SERVICES AVAILABLE", greenIcon));

            return gson.toJson(frames);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    FrameWrapper frames = new FrameWrapper(new ArrayList<>());
    frames.addFrame(mojangLaunch);
    frames.addFrame(new Frame("ERROR: Failed to parse json.", redIcon));

    return gson.toJson(frames);
}

From source file:com.getperka.flatpack.codexes.EntityCodex.java

License:Apache License

public void readProperties(T object, JsonObject element, DeserializationContext context) {
    context.pushPath("(EntityCodex.readProperties())" + object.getUuid());

    try {/*from ww  w  . ja  v a2  s .c o m*/
        // Ignore incoming data with just a UUID value to avoid unnecessary warnings
        if (element.entrySet().size() == 1 && element.has("uuid")) {
            return;
        }

        if (!context.checkAccess(object)) {
            return;
        }

        // Allow the object to see the data that's about to be applied
        for (Method m : preUnpackMethods) {
            if (m.getParameterTypes().length == 0) {
                m.invoke(object);
            } else {
                m.invoke(object, element);
            }
        }

        List<String> roles = context.getRoles();
        for (Property prop : typeContext.extractProperties(clazz)) {
            if (!prop.maySet(roles)) {
                continue;
            }

            String simplePropertyName = prop.getName();
            context.pushPath("." + simplePropertyName);
            try {
                Object value;
                if (prop.isEmbedded()) {
                    /*
                     * Embedded objects are never referred to by uuid in the payload, so an instance will
                     * need to be allocated before reading in the properties.
                     */
                    @SuppressWarnings("unchecked")
                    EntityCodex<HasUuid> codex = (EntityCodex<HasUuid>) prop.getCodex();
                    HasUuid embedded = codex.allocate(UUID.randomUUID(), context, false);
                    codex.readProperties(embedded, element, context);
                    value = embedded;
                } else {

                    @SuppressWarnings("unchecked")
                    Codex<Object> codex = (Codex<Object>) prop.getCodex();

                    // merchant would become merchantUuid
                    String payloadPropertyName = simplePropertyName + codex.getPropertySuffix();

                    // Ignore undefined property values, while allowing explicit nullification
                    if (!element.has(payloadPropertyName)) {
                        continue;
                    }

                    value = codex.read(element.get(payloadPropertyName), context);
                }

                if (value == null && prop.getSetter().getParameterTypes()[0].isPrimitive()) {
                    // Don't try to pass a null to a primitive setter
                    continue;
                }

                // Perhaps set the other side of a OneToMany relationship
                Property impliedPropery = prop.getImpliedProperty();
                if (impliedPropery != null && value != null) {
                    // Ensure that any linked property is also mutable
                    if (!impliedPropery.maySet(roles) || !checkAccess(value, context)) {
                        context.addWarning(object,
                                "Ignoring property %s because the inverse relationship (%s) may not be set",
                                prop.getName(), impliedPropery.getName());
                        continue;
                    }
                    context.addPostWork(new ImpliedPropertySetter(context, impliedPropery, value, object));
                }

                // Set the value
                prop.getSetter().invoke(object, value);

                // Record the value as having been set
                context.addModified(object, prop);
            } catch (Exception e) {
                context.fail(e);
            } finally {
                context.popPath();
            }
        }
    } catch (Exception e) {
        context.fail(e);
    } finally {
        context.popPath();
    }
}

From source file:com.github.autermann.matlab.json.MatlabRequestSerializer.java

License:Open Source License

@Override
public MatlabRequest deserialize(JsonElement elem, Type type, JsonDeserializationContext ctx)
        throws JsonParseException {
    JsonObject json = elem.getAsJsonObject();
    String function = json.get(MatlabJSONConstants.FUNCTION).getAsString();
    MatlabRequest request = new MatlabRequest(function);

    JsonObject results = json.get(MatlabJSONConstants.RESULTS).getAsJsonObject();
    for (Entry<String, JsonElement> result : results.entrySet()) {
        request.addResult(result.getKey(), parseType(result.getValue()));
    }//from www.j  a va  2  s  . c  om

    JsonArray parameters = json.get(MatlabJSONConstants.PARAMETERS).getAsJsonArray();
    for (JsonElement parameter : parameters) {
        MatlabValue value = ctx.deserialize(parameter, MatlabValue.class);
        request.addParameter(value);
    }

    return request;
}

From source file:com.github.autermann.matlab.json.MatlabResultSerializer.java

License:Open Source License

@Override
public MatlabResult deserialize(JsonElement elem, Type type, JsonDeserializationContext ctx)
        throws JsonParseException {
    MatlabResult mlresult = new MatlabResult();
    JsonObject results = elem.getAsJsonObject().get(MatlabJSONConstants.RESULTS).getAsJsonObject();

    for (Entry<String, JsonElement> result : results.entrySet()) {
        MatlabValue value = ctx.deserialize(result.getValue(), MatlabValue.class);
        mlresult.addResult(result.getKey(), value);
    }//from w ww .ja  v a 2  s  . co  m
    return mlresult;
}

From source file:com.github.daytron.daytronmoney.conversion.CurrencyExchange.java

License:Open Source License

/**
 * Creates an instance private. Connects to API and extract latest currency
 * rates from its JSOn file. Saves the currency rates into a
 * <code>Map</code> object. Purpose of list is for currency code
 * verification in conversion process.//from   www  .  ja  v a2 s  .  c o  m
 */
private CurrencyExchange() {
    JsonObject tempObject;
    try {
        tempObject = ConversionClient.getLatestRatesJsonObject();
    } catch (MoneyConversionException ex) {
        Logger.getLogger(CurrencyExchange.class.getName()).log(Level.SEVERE, null, ex);
        throw new InstantiationError("Cannot connect to the API.");
    }

    Set<Map.Entry<String, JsonElement>> rateList = tempObject.entrySet();

    // Creates a copy
    this.listOfRates = new ConcurrentHashMap<>();

    for (Map.Entry<String, JsonElement> rateItem : rateList) {
        listOfRates.put(rateItem.getKey(), rateItem.getValue().getAsString());
    }
}

From source file:com.github.easyjsonapi.adapters.EasyJsonApiDeserializer.java

License:Apache License

/**
 * Deserializer relationships json object
 * /*from   www  .ja v  a  2  s  .c  o m*/
 * @param jsonRelationships
 *            the relationship json object
 * @param jsonContext
 *            the json context
 * @return one instance of {@link Relationships}
 */
private Relationships deserializerDataRelationship(JsonObject json, JsonDeserializationContext jsonContext) {

    Relationships relationships = new Relationships();
    Link link = Nullable.LINK;
    LinkRelated linkRelated = Nullable.LINK_RELATED;
    Object metaRelated = Nullable.OBJECT;

    JsonObject jsonRels = json.get("relationships").getAsJsonObject();

    for (Entry<String, JsonElement> jsonRelationship : jsonRels.entrySet()) {

        Relationship relationship = Nullable.RELATIONSHIP;

        JsonObject jsonRelationshipValue = jsonRelationship.getValue().getAsJsonObject();

        String jsonRelationshipKey = Assert.isNull(jsonRelationship.getKey()) ? null
                : jsonRelationship.getKey();

        if (Assert.notNull(jsonRelationshipValue)) {

            if (Assert.notEmpty(jsonRelationshipKey) && jsonRelationshipKey.toLowerCase().equals("meta")) {

                metaRelated = deserializerObject("meta", jsonRelationshipValue, EasyJsonApiTypeToken.TOKEN_META,
                        jsonContext);

            }

            JsonObject relsLinks = Assert.isNull(jsonRelationshipValue.get("links")) ? null
                    : jsonRelationshipValue.get("links").getAsJsonObject();
            JsonArray relsData = Assert.isNull(jsonRelationshipValue.get("data")) ? null
                    : jsonRelationshipValue.get("data").getAsJsonArray();

            if (Assert.notNull(relsLinks)) {

                String self = JsonTools.getStringInsideJson("self", relsLinks);
                JsonObject related = Assert.isNull(relsLinks.get("related")) ? null
                        : relsLinks.get("related").getAsJsonObject();

                if (Assert.notNull(related)) {

                    String href = JsonTools.getStringInsideJson("href", related);

                    Object metaLinkRelated = deserializerObject("meta", related,
                            EasyJsonApiTypeToken.TOKEN_META_RELATIONSHIP, jsonContext);

                    linkRelated = new LinkRelated(href, metaLinkRelated);

                }

                link = new Link(linkRelated, self);
            }

            relationship = new Relationship(jsonRelationshipKey, link, metaRelated);

            if (Assert.notNull(relsData) && Assert.notNull(relationships)) {

                for (JsonElement data : relsData) {
                    JsonObject dataRels = data.getAsJsonObject();

                    String id = JsonTools.getStringInsideJson("id", dataRels);
                    String type = JsonTools.getStringInsideJson("type", dataRels);

                    relationship.addDataLinkage(new DataLinkage(id, type));
                }
            }

            relationships.getRelationships().add(relationship);
        }
    }

    return relationships;
}

From source file:com.github.francescojo.gsondbg.GsonDebuggable.java

private void inspectJsonObject(JsonObject jsonObject, Class<?> klass) {
    Map<String, Field> mappingInfo = new HashMap<String, Field>();
    for (Field classField : klass.getDeclaredFields()) {
        Annotation[] annotations = classField.getAnnotations();
        if (null == annotations || 0 == annotations.length) {
            mappingInfo.put(classField.getName(), classField);
        } else {//from   ww w. ja  va2  s . co m
            for (Annotation annotation : annotations) {
                if (annotation instanceof SerializedName) {
                    String customName = ((SerializedName) annotation).value();
                    mappingInfo.put(customName, classField);
                    /*
                     * FIXME: alternate() is introduced in Gson 2.4. Safe to delete if your Gson is lower than 2.4.
                     */
                    try {
                        String[] alternateNames = ((SerializedName) annotation).alternate();
                        for (String alternateName : alternateNames) {
                            mappingInfo.put(alternateName, classField);
                        }
                    } catch (NoSuchMethodError ignore) {
                    }
                }
            }
        }
    }

    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        if (!mappingInfo.containsKey(key)) {
            /*
             * Gson ignores fields that are not found in json by default - following same rule in here.
             */
            continue;
        }

        Field javaField = mappingInfo.get(key);
        Class<?> javaType = javaField.getType();

        if (WellKnownTypeCastingRules.isWellKnown(javaType)) {
            if (!(value instanceof JsonPrimitive)) {
                log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }",
                        javaField.getDeclaringClass().getName(), javaField.getName(),
                        javaField.getType().getCanonicalName(), key, value);
                continue;
            }

            WellKnownTypeCastingRules rule = WellKnownTypeCastingRules.byJavaType(javaType);
            JsonPrimitive primitive = value.getAsJsonPrimitive();
            if (rule.isAcceptable(primitive)) {
                continue;
            }

            log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }",
                    javaField.getDeclaringClass().getName(), javaField.getName(),
                    javaField.getType().getCanonicalName(), key, value);
        } else if (javaType.isArray()) {
            try {
                gson.fromJson(value, javaType);
            } catch (JsonSyntaxException e) {
                log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }",
                        javaField.getDeclaringClass().getName(), javaField.getName(),
                        javaField.getType().getCanonicalName(), key, value);
            }
        } else if (value.isJsonObject()) {
            inspectJsonObject(value.getAsJsonObject(), javaType);
        }
    }
}

From source file:com.github.GsonPrettyPrinter.java

License:Open Source License

private List<String> objectToStringList(final JsonObject jsonObject) {
    final Map<String, List<String>> slm = new HashMap<String, List<String>>();
    for (final Entry<String, JsonElement> e : jsonObject.entrySet()) {
        slm.put(e.getKey(), toStringList(e.getValue()));
    }/*from ww  w  .jav a 2 s.c  o m*/
    // Can we fit the object on a single line?
    boolean oneLine = true;
    int approxLineLength = 0;
    for (final Entry<String, List<String>> e : slm.entrySet()) {
        if (e.getValue().size() > 1) {
            oneLine = false;
            break;
        }
        approxLineLength += e.getKey().length() + e.getValue().get(0).length() + 6;
    }
    if (approxLineLength > MAX_LEN_FOR_ONE_LINE) {
        oneLine = false;
    }
    if (oneLine) {
        final StringBuffer sb = new StringBuffer(approxLineLength * 2 + 10);
        sb.append("{");
        boolean first = true;
        for (final Entry<String, List<String>> e : orderEntrySet(slm.entrySet())) {
            if (!first) {
                sb.append(", ");
            }
            first = false;
            sb.append("\"" + e.getKey() + "\" : " + e.getValue().get(0));
        }
        sb.append("}");
        return Collections.singletonList(sb.toString());
    }
    final LinkedList<String> ret = new LinkedList<String>();
    ret.add("{");
    int oPos = 0;
    for (final Entry<String, List<String>> e : orderEntrySet(slm.entrySet())) {
        oPos++;
        final int slLen = e.getValue().size();
        int pos = 0;
        for (final String s : e.getValue()) {
            pos++;
            final boolean needComma = (pos == slLen && oPos < slm.size());
            if (pos == 1) {
                ret.add(indent + "\"" + e.getKey() + "\" : " + s + (needComma ? ", " : ""));
            } else {
                ret.add(indent + s + (needComma ? ", " : ""));
            }
        }
    }
    ret.add("}");
    return ret;
}

From source file:com.github.nyrkovalex.deploy.me.parsing.Parser.java

License:Open Source License

Set<Server> parse(JsonObject jsonObject, Iterable<Fileset> filesets) {
    Map<String, Fileset> filesetIndex = Maps.uniqueIndex(filesets, Named::name);
    return jsonObject.entrySet().stream()
            .map(entry -> serverParser.parse(entry.getKey(), filesetIndex, entry.getValue())).collect(toSet());
}