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.jbirdvegas.mgerrit.objects.Projects.java

License:Apache License

@Override
public Projects deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext deserializationContext) throws JsonParseException {

    JsonObject json = jsonElement.getAsJsonObject();
    for (Map.Entry<String, JsonElement> project : json.entrySet()) {
        String path = project.getKey();
        JsonObject details = project.getValue().getAsJsonObject();
        String id = details.get("id").getAsString();
        projects.add(new Project(path, id));
    }//  w  w  w  .j  a  va2  s .  c om

    return this;
}

From source file:com.jcwhatever.nucleus.storage.JsonDataNode.java

License:MIT License

private void getAllValuesRecursive(JsonObject object, String basePath, Map<String, Object> result) {

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

    for (Map.Entry<String, JsonElement> entry : entrySet) {
        String name = basePath.isEmpty() ? entry.getKey() : basePath + '.' + entry.getKey();
        JsonElement element = entry.getValue();

        if (element.isJsonObject()) {
            getAllValuesRecursive(element.getAsJsonObject(), name, result);
        } else {/*www .  jav a  2s. c o  m*/
            result.put(name, element.getAsString());
        }
    }
}

From source file:com.jinglingtec.ijiazu.util.CCPRestSmsSDK.java

License:Open Source License

private HashMap<String, Object> jsonToMap(String result) {
    HashMap<String, Object> hashMap = new HashMap<String, Object>();
    JsonParser parser = new JsonParser();
    JsonObject asJsonObject = parser.parse(result).getAsJsonObject();
    Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
    HashMap<String, Object> hashMap2 = new HashMap<String, Object>();

    for (Entry<String, JsonElement> m : entrySet) {
        if ("statusCode".equals(m.getKey()) || "statusMsg".equals(m.getKey())) {
            hashMap.put(m.getKey(), m.getValue().getAsString());
        } else {/* ww  w . ja v a  2 s .com*/
            if ("SubAccount".equals(m.getKey()) || "totalCount".equals(m.getKey()) || "token".equals(m.getKey())
                    || "downUrl".equals(m.getKey())) {
                if (!"SubAccount".equals(m.getKey())) {
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                } else {
                    try {
                        if ((m.getValue().toString().trim().length() <= 2)
                                && !m.getValue().toString().contains("[")) {
                            hashMap2.put(m.getKey(), m.getValue().getAsString());
                            hashMap.put("data", hashMap2);
                            break;
                        }
                        if (m.getValue().toString().contains("[]")) {
                            hashMap2.put(m.getKey(), new JsonArray());
                            hashMap.put("data", hashMap2);
                            continue;
                        }
                        JsonArray asJsonArray = parser.parse(m.getValue().toString()).getAsJsonArray();
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        for (JsonElement j : asJsonArray) {
                            Set<Entry<String, JsonElement>> entrySet2 = j.getAsJsonObject().entrySet();
                            HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                            for (Entry<String, JsonElement> m2 : entrySet2) {
                                hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                            }
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put("SubAccount", arrayList);
                    } catch (Exception e) {
                        JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                        Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Entry<String, JsonElement> m2 : entrySet2) {
                            hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                        }
                        hashMap2.put(m.getKey(), hashMap3);
                        hashMap.put("data", hashMap2);
                    }

                }
                hashMap.put("data", hashMap2);
            } else {

                JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                for (Entry<String, JsonElement> m2 : entrySet2) {
                    hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                }
                if (hashMap3.size() != 0) {
                    hashMap2.put(m.getKey(), hashMap3);
                } else {
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                }
                hashMap.put("data", hashMap2);
            }
        }
    }
    return hashMap;
}

From source file:com.jomofisher.tests.cmake.JsonUtils.java

License:Apache License

private static void checkJsonObjectAgainstJavaMap(JsonObject jsonObject, Field field) {
    Type valueClass = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[1];
    for (Entry<String, JsonElement> element : jsonObject.entrySet()) {
        checkJsonElementAgainstJavaType(element.getValue(), (Class) valueClass);
    }/*  w  w w.j  av a  2 s  . c o  m*/

}

From source file:com.jomofisher.tests.cmake.JsonUtils.java

License:Apache License

private static void checkJsonObjectAgainstJava(JsonObject jsonObject, Field field) {
    if (field.getType() == java.util.Map.class) {
        checkJsonObjectAgainstJavaMap(jsonObject, field);
        return;//from ww w . java 2  s  .c  om
    }
    Map<String, Field> fieldNames = getFieldNames(field.getType());
    for (Entry<String, JsonElement> element : jsonObject.entrySet()) {
        Field subField = fieldNames.get(element.getKey());
        if (fieldNames.get(element.getKey()) == null) {
            throw new RuntimeException(String.format("Did not find field %s in class %s for JSon: %s",
                    element.getKey(), subField, jsonObject));
        }
        checkJsonElementAgainstJava(element.getValue(), subField);
    }
}

From source file:com.jomofisher.tests.cmake.JsonUtils.java

License:Apache License

private static void checkJsonObjectAgainstJavaType(JsonObject jsonObject, Class clazz) {
    Map<String, Field> fieldNames = getFieldNames(clazz);
    for (Entry<String, JsonElement> element : jsonObject.entrySet()) {
        Field field = fieldNames.get(element.getKey());
        if (fieldNames.get(element.getKey()) == null) {
            throw new RuntimeException(String.format("Did not find field %s in class %s for JSon: %s",
                    element.getKey(), clazz.getSimpleName(), jsonObject));
        }//  w  ww  . j a  v  a  2 s  .c  o m
        checkJsonElementAgainstJava(element.getValue(), field);
    }
}

From source file:com.kotcrab.vis.editor.serializer.json.IntMapJsonSerializer.java

License:Apache License

@Override
public IntMap<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonArray jsonArray = json.getAsJsonArray();

    IntMap<T> intMap = new IntMap<>(jsonArray.size());

    for (JsonElement element : jsonArray) {
        JsonObject object = element.getAsJsonObject();
        Entry<String, JsonElement> entry = object.entrySet().iterator().next();
        int mapKey = Integer.parseInt(entry.getKey());
        Class<?> mapObjectClass = GsonUtils.readClassProperty(object, context);
        intMap.put(mapKey, context.deserialize(entry.getValue(), mapObjectClass));
    }//from  w  w  w .j av  a  2s .com

    return intMap;
}

From source file:com.kotcrab.vis.editor.serializer.json.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (baseType.isAssignableFrom(type.getRawType()) == false) {
        return null;
    }//w w w  .ja v a2 s  .c  o  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    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, 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);
        }
    };
}

From source file:com.kurento.kmf.jsonrpcconnector.JsonUtils.java

License:Open Source License

@Override
public Props deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (!(json instanceof JsonObject)) {
        throw new JsonParseException("Cannot convert " + json + " to Props object");
    }//  w  w w.  ja va2  s .  c  o  m

    JsonObject jObject = (JsonObject) json;

    Props props = new Props();
    for (Map.Entry<String, JsonElement> e : jObject.entrySet()) {
        Object value = deserialize(e.getValue(), context);
        props.add(e.getKey(), value);
    }
    return props;
}

From source file:com.kurtraschke.amtkgtfsrealtime.AMTKRealtimeProvider.java

License:Apache License

/**
 * This method downloads the latest vehicle data, processes each vehicle in
 * turn, and create a GTFS-realtime feed of trip updates and vehicle
 * positions as a result./*from ww  w . j a  v a2  s.c  om*/
 */
private void refreshVehicles() throws IOException, ParseException {
    URL trainPositions = new URL(
            "https://www.googleapis.com/mapsengine/v1/tables/01382379791355219452-08584582962951999356/features?version=published&maxResults=250&key="
                    + _mapsEngineKey);

    JsonParser parser = new JsonParser();
    JsonObject o = (JsonObject) parser.parse(new InputStreamReader(trainPositions.openStream()));

    JsonArray trains = o.getAsJsonArray("features");

    for (JsonElement e : trains) {
        try {
            JsonObject train = e.getAsJsonObject();

            JsonArray coordinates = train.getAsJsonObject("geometry").getAsJsonArray("coordinates");

            JsonObject trainProperties = train.getAsJsonObject("properties");

            String trainState = trainProperties.get("TrainState").getAsString();

            if (!(trainState.equals("Active") || trainState.equals("Predeparture"))) {
                continue;
            }

            String trainNumber = trainProperties.get("TrainNum").getAsString();

            String originTimestamp = trainProperties.get("OrigSchDep").getAsString();
            String originTimezone = trainProperties.get("OriginTZ").getAsString();

            String updateTimestamp = trainProperties.get("LastValTS").getAsString();

            String updateTimezone = trainProperties.has("EventTZ")
                    ? trainProperties.get("EventTZ").getAsString()
                    : originTimezone;

            ServiceDate trainServiceDate = DateUtils.serviceDateForTimestamp(originTimestamp, originTimezone);

            String key = String.format("%s(%s)", trainNumber, trainServiceDate.getDay());

            Date updateDate = DateUtils.parseTimestamp(updateTimestamp, updateTimezone);

            if (!lastUpdateByVehicle.containsKey(key) || updateDate.after(lastUpdateByVehicle.get(key))) {
                long updateTime = updateDate.getTime() / 1000L;

                /**
                 * We construct a TripDescriptor and VehicleDescriptor,
                 * which will be used in both trip updates and vehicle
                 * positions to identify the trip and vehicle.
                 */
                TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder();

                String tripId = tripForTrainAndDate(trainNumber, trainServiceDate);

                if (tripId == null) {
                    continue;
                }

                tripDescriptor.setTripId(tripId);
                tripDescriptor.setStartDate(String.format("%04d%02d%02d", trainServiceDate.getYear(),
                        trainServiceDate.getMonth(), trainServiceDate.getDay()));

                VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder();
                vehicleDescriptor.setId(key);
                vehicleDescriptor.setLabel(trainNumber);

                TripUpdate.Builder tripUpdate = TripUpdate.newBuilder();

                for (Entry<String, JsonElement> propEntry : trainProperties.entrySet()) {
                    if (propEntry.getKey().startsWith("Station")) {
                        StopTimeUpdate stu = stopTimeUpdateForStation(propEntry.getValue().getAsString());
                        if (stu != null) {
                            tripUpdate.addStopTimeUpdate(stu);
                        }
                    }
                }

                tripUpdate.setTrip(tripDescriptor);
                tripUpdate.setVehicle(vehicleDescriptor);
                tripUpdate.setTimestamp(updateTime);
                /**
                 * Create a new feed entity to wrap the trip update and add
                 * it to the GTFS-realtime trip updates feed.
                 */
                FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder();
                tripUpdateEntity.setId(key);
                tripUpdateEntity.setTripUpdate(tripUpdate);

                /**
                 * To construct our VehiclePosition, we create a position
                 * for the vehicle. We add the position to a VehiclePosition
                 * builder, along with the trip and vehicle descriptors.
                 */
                Position.Builder position = Position.newBuilder();
                position.setLatitude(coordinates.get(1).getAsFloat());
                position.setLongitude(coordinates.get(0).getAsFloat());

                if (trainProperties.has("Heading")
                        && !trainProperties.get("Heading").getAsString().equals("")) {
                    position.setBearing(degreesForHeading(trainProperties.get("Heading").getAsString()));
                }

                if (trainProperties.has("Velocity")
                        && !trainProperties.get("Velocity").getAsString().equals("")) {
                    position.setSpeed(trainProperties.get("Velocity").getAsFloat() * 0.44704f);
                }

                VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder();
                vehiclePosition.setTimestamp(updateTime);
                vehiclePosition.setPosition(position);
                vehiclePosition.setTrip(tripDescriptor);
                vehiclePosition.setVehicle(vehicleDescriptor);

                /**
                 * Create a new feed entity to wrap the vehicle position and
                 * add it to the GTFS-realtime vehicle positions feed.
                 */
                FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder();
                vehiclePositionEntity.setId(key);
                vehiclePositionEntity.setVehicle(vehiclePosition);

                GtfsRealtimeIncrementalUpdate tripUpdateUpdate = new GtfsRealtimeIncrementalUpdate();
                tripUpdateUpdate.addUpdatedEntity(tripUpdateEntity.build());
                _tripUpdatesSink.handleIncrementalUpdate(tripUpdateUpdate);

                GtfsRealtimeIncrementalUpdate vehiclePositionUpdate = new GtfsRealtimeIncrementalUpdate();
                vehiclePositionUpdate.addUpdatedEntity(vehiclePositionEntity.build());
                _vehiclePositionsSink.handleIncrementalUpdate(vehiclePositionUpdate);

                if (trainProperties.has("StatusMsg")) {
                    String statusMessage = trainProperties.get("StatusMsg").getAsString().trim();
                    Alert.Builder alert = Alert.newBuilder();

                    alert.setDescriptionText(GtfsRealtimeLibrary.getTextAsTranslatedString(statusMessage));

                    EntitySelector.Builder informedEntity = EntitySelector.newBuilder();
                    informedEntity.setTrip(tripDescriptor);

                    alert.addInformedEntity(informedEntity);

                    FeedEntity.Builder alertEntity = FeedEntity.newBuilder();
                    alertEntity.setId(key);
                    alertEntity.setAlert(alert);

                    GtfsRealtimeIncrementalUpdate alertUpdate = new GtfsRealtimeIncrementalUpdate();
                    alertUpdate.addUpdatedEntity(alertEntity.build());
                    _alertsSink.handleIncrementalUpdate(alertUpdate);
                }

                lastUpdateByVehicle.put(key, updateDate);
            }
        } catch (Exception ex) {
            _log.warn("Exception processing vehicle", ex);
        }

    }

}