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.mediamath.terminalone.service.ReportService.java

License:Apache License

/**
 * this method parses meta query response.
 * /*from  w  w  w . j  a v  a2s .  c  om*/
 * @param response
 *          requires the JSON response.
 * @return JsonResponse<? extends T1Entity> returns JsonResponse of type T.
 * 
 */
public JsonResponse<? extends T1Entity> parseMetaResponse(String response) {
    JsonParser parser = new JsonParser();
    JsonResponse<Meta> finalResponse = null;
    JsonObject obj = parser.parse(response).getAsJsonObject();

    JsonElement reportsElement = obj.get("reports");
    JsonObject reportsObj = reportsElement.getAsJsonObject();

    if (reportsObj != null) {

        Meta meta = new Meta();
        Type type = new TypeToken<MetaData>() {
        }.getType();
        HashMap<String, MetaData> metaData = new HashMap<String, MetaData>();

        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);
        Gson gson = builder.create();

        for (Entry<String, JsonElement> a : reportsObj.entrySet()) {
            String key = a.getKey();
            MetaData value = gson.fromJson(a.getValue(), type);
            metaData.put(key, value);
        }
        meta.setMetaData(metaData);
        finalResponse = new JsonResponse<Meta>(meta);
    }

    return finalResponse;
}

From source file:com.mediamath.terminalone.service.ReportService.java

License:Apache License

/**
 * parses the meta data response for a particular report query.
 * // w  w w. jav a2s.co m
 * @param response
 *          requires JSON response.
 * @return MetaData object.
 */
public MetaData parseReportMetaResponse(String response) {

    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);
    Gson gson = builder.create();
    MetaData data = gson.fromJson(response, MetaData.class);

    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();
    JsonElement reportsElement = obj.get("structure");

    JsonObject dimensionObj = reportsElement.getAsJsonObject().get("dimensions").getAsJsonObject();
    JsonObject metricsObj = reportsElement.getAsJsonObject().get("metrics").getAsJsonObject();
    JsonObject timefieldObj = reportsElement.getAsJsonObject().get("time_field").getAsJsonObject();

    // dimensions
    if (dimensionObj != null) {
        MetaDimensions dimensions = new MetaDimensions();
        HashMap<String, MetaDimensionData> dimensionsInfoMap = new HashMap<String, MetaDimensionData>();

        for (Entry<String, JsonElement> a : dimensionObj.entrySet()) {
            String key = a.getKey();
            MetaDimensionData value = gson.fromJson(a.getValue(), MetaDimensionData.class);
            dimensionsInfoMap.put(key, value);
        }

        dimensions.setDimensionsInfoMap(dimensionsInfoMap);
        data.getStructure().setDimensions(dimensions);
    }

    // metrics
    if (metricsObj != null) {
        MetaMetrics metrics = new MetaMetrics();
        HashMap<String, MetricsData> metricsMap = new HashMap<String, MetricsData>();

        for (Entry<String, JsonElement> a : metricsObj.entrySet()) {
            String key = a.getKey();
            MetricsData value = gson.fromJson(a.getValue(), MetricsData.class);
            metricsMap.put(key, value);
        }

        metrics.setMetricsMap(metricsMap);
        data.getStructure().setMetrics(metrics);
    }

    // time_field
    if (timefieldObj != null) {

        TimeField timefield = new TimeField();
        HashMap<String, TimeInterval> timeFieldMap = new HashMap<String, TimeInterval>();

        for (Entry<String, JsonElement> a : timefieldObj.entrySet()) {
            String key = a.getKey();
            TimeInterval value = gson.fromJson(a.getValue(), TimeInterval.class);
            timeFieldMap.put(key, value);
        }

        timefield.setData(timeFieldMap);
        data.getStructure().setTimeField(timefield);
    }

    return data;
    // end
}

From source file:com.metinkale.prayerapp.vakit.times.gson.RuntimeTypeAdapterFactory.java

License:Apache License

@Override
public <R> TypeAdapter<R> create(@NonNull Gson gson, @NonNull TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*w  ww  .ja  va2 s.co m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, @NonNull R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:com.michaelfotiadis.crossyscore.core.data.parsers.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(final Gson gson, final TypeToken<R> type) {
    if (!type.getRawType().equals(baseType)) {
        return null;
    }/*from  w  ww.j  a va 2 s .c o m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();

    for (final Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public void write(final JsonWriter out, final R value) throws IOException {
            if (value != null) {
                final Class<?> srcType = value.getClass();
                final String label = subtypeToLabel.get(srcType);
                @SuppressWarnings("unchecked")
                final // registration requires that subtype extends T
                TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
                if (delegate == null) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + "; did you forget to register a subtype?");
                }
                final JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
                if (jsonObject.has(typeFieldName)) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + " because it already defines a field named " + typeFieldName);
                }
                final JsonObject clone = new JsonObject();
                clone.add(typeFieldName, new JsonPrimitive(label));
                for (final Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                out.nullValue();
            }
        }

        @Override
        public R read(final JsonReader in) throws IOException {
            final JsonElement jsonElement = Streams.parse(in);
            // fix for null Json Elements
            if (jsonElement.isJsonNull()) {
                return null;
            }

            final JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            final String label = getBaseTypeLabel(labelJsonElement);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            final TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);

            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }

            return delegate.fromJsonTree(jsonElement);
        }

        private String getBaseTypeLabel(final JsonElement labelJsonElement) {
            final String label;

            if (labelJsonElement == null) {
                if (defaultSubTypeLabel == null) {
                    throw new JsonParseException("cannot deserialize " + baseType
                            + " because it does not define a field named " + typeFieldName);
                } else {
                    label = defaultSubTypeLabel;

                    if (!labelToDelegate.containsKey(label)) {
                        throw new IllegalStateException(
                                "WTF: Was looking for " + label + " in " + labelToDelegate.keySet());
                    }

                }
            } else {
                label = labelJsonElement.getAsString();
            }

            return label;
        }
    };
}

From source file:com.michaelfotiadis.steam.net.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(final Gson gson, final TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from ww  w.java  2s .  c  o  m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();

    for (final Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        private String getBaseTypeLabel(final JsonElement labelJsonElement) {
            final String label;

            if (labelJsonElement == null) {
                if (defaultSubTypeLabel == null) {
                    throw new JsonParseException("cannot deserialize " + baseType
                            + " because it does not define a field named " + typeFieldName);
                } else {
                    label = defaultSubTypeLabel;

                    if (!labelToDelegate.containsKey(label)) {
                        throw new IllegalStateException(
                                "WTF: Was looking for " + label + " in " + labelToDelegate.keySet());
                    }

                }
            } else {
                label = labelJsonElement.getAsString();
            }

            return label;
        }

        @Override
        public R read(final JsonReader in) throws IOException {
            final JsonElement jsonElement = Streams.parse(in);
            // fix for null Json Elements
            if (jsonElement.isJsonNull()) {
                return null;
            }

            final JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            final String label = getBaseTypeLabel(labelJsonElement);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            final TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);

            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }

            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(final JsonWriter out, final R value) throws IOException {
            if (value != null) {
                final Class<?> srcType = value.getClass();
                final String label = subtypeToLabel.get(srcType);
                @SuppressWarnings("unchecked")
                final // registration requires that subtype extends T
                TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
                if (delegate == null) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + "; did you forget to register a subtype?");
                }
                final JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
                if (jsonObject.has(typeFieldName)) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + " because it already defines a field named " + typeFieldName);
                }
                final JsonObject clone = new JsonObject();
                clone.add(typeFieldName, new JsonPrimitive(label));
                for (final Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                out.nullValue();
            }
        }
    };
}

From source file:com.microsoft.applicationinsights.contracts.ContainerStateEvent.java

License:Open Source License

private void deserialize(String json) {
    JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
    this.eventName = jsonObj.get("name").getAsString();
    this.ikey = jsonObj.get("ikey").getAsString();

    JsonObject propertiesObject = jsonObj.getAsJsonObject("properties");

    for (Map.Entry<String, JsonElement> kv : propertiesObject.entrySet()) {
        this.properties.put(kv.getKey(), kv.getValue().getAsString());
    }//from  w  w  w .java  2  s .  c om
}

From source file:com.microsoft.Malmo.MissionHandlers.ObservationFromServer.java

License:Open Source License

@Override
public void writeObservationsToJSON(JsonObject json, MissionInit missionInit) {
    String jsonstring = "";
    synchronized (this.latestJsonStats) {
        jsonstring = this.latestJsonStats;
    }/*from   w  w  w .  j  a va  2s  .  co  m*/
    if (jsonstring.length() > 2) // "{}" is the empty JSON string.
    {
        // Parse the string into json:
        JsonParser parser = new JsonParser();
        JsonElement root = parser.parse(jsonstring);
        // Now copy the children of root into the provided json object:
        if (root.isJsonObject()) {
            JsonObject rootObj = root.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : rootObj.entrySet()) {
                json.add(entry.getKey(), entry.getValue());
            }
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceJsonTable.java

License:Open Source License

/**
 * Updates the JsonObject to have an id property
 * @param json/*from  w w  w.  ja  va2  s . com*/
 *            the element to evaluate
 */
private void updateIdProperty(final JsonObject json) throws IllegalArgumentException {
    for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
        String key = entry.getKey();
        if (key.equalsIgnoreCase("id")) {
            JsonElement element = entry.getValue();
            if (isValidTypeId(element)) {
                if (!key.equals("id")) {
                    //force the id name to 'id', no matter the casing 
                    json.remove(key);
                    // Create a new id property using the given property name
                    json.addProperty("id", entry.getValue().getAsNumber());
                }
                return;
            } else {
                throw new IllegalArgumentException("The id must be numeric");
            }
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTableBase.java

License:Open Source License

/**
 * Removes all system properties (name start with '__') from the instance if
 * the instance is determined to have a string id and therefore be for table
 * that supports system properties./*from   w w  w  .  j a va 2  s  .c om*/
 *
 * @param instance The instance to remove the system properties from.
 * @param version  Set to the value of the version system property before it is
 *                 removed.
 * @return The instance with the system properties removed.
 */
protected static JsonObject removeSystemProperties(JsonObject instance) {
    boolean haveCloned = false;

    for (Entry<String, JsonElement> property : instance.entrySet()) {
        if (SystemPropertyNameToEnum.containsKey(property.getKey())) {
            // We don't want to alter the original JsonObject passed in by
            // the caller
            // so if we find a system property to remove, we have to clone
            // first
            if (!haveCloned) {
                instance = (JsonObject) new JsonParser().parse(instance.toString());
                haveCloned = true;
            }

            instance.remove(property.getKey());
        }
    }

    return instance;
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTableBase.java

License:Open Source License

/**
 * Gets the version system property.//  w w  w  .  j  a v a  2  s  .c o m
 *
 * @param instance The instance to remove the system properties from.
 * @return The value of the version system property or null if none present.
 */
protected static String getVersionSystemProperty(JsonObject instance) {
    String version = null;

    for (Entry<String, JsonElement> property : instance.entrySet()) {
        if (property.getKey().equalsIgnoreCase(VersionSystemPropertyName)
                && !property.getValue().isJsonNull()) {
            version = property.getValue().getAsString();
        }
    }

    return version;
}