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.sixteencolorgames.rpg.pathfindertools.misc.Race.java

private void processTraits() {
    getTraits().forEach((JsonObject trait) -> {
        trait.entrySet().forEach((entry) -> {
            String key = entry.getKey();
            if ("skill.extra".equals(key)) {
                PathfinderTools.instance.charBuild.skills.skillExtra
                        .append(entry.getValue().getAsString() + "\n");
            } else if (key.startsWith("skill.")) {
                Skill skill = Skill.valueOf(key.substring(6).toUpperCase());
                PathfinderTools.instance.charBuild.skills.racialMod.get(skill)
                        .setValue(entry.getValue().getAsInt());
            }//  w  w w.  jav a 2  s . com
        });
    });
}

From source file:com.skelril.skree.service.internal.zone.allocator.ZonePool.java

License:Mozilla Public License

public void load() throws IOException, IllegalStateException {
    globalBoxList.clear();//from w  ww.  ja v a  2  s  .c o  m
    cacheRegions.clear();
    regionQueue.clear();

    Gson gson = new GsonBuilder().create();
    JsonParser parser = new JsonParser();

    try (BufferedReader reader = Files.newBufferedReader(getCacheFile())) {
        JsonObject object = parser.parse(reader).getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            String manager = entry.getKey();

            JsonArray elements = entry.getValue().getAsJsonArray();
            for (JsonElement element : elements) {
                ZoneBoundingBox boundingBox = gson.fromJson(element, ZoneBoundingBox.class);
                noSaveClaimNew(manager, boundingBox);
                freeToPool(manager, boundingBox);
            }
        }
    }
}

From source file:com.skyisland.questmanager.fanciful.FancyMessage.java

License:Open Source 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 FancyMessage} representing the parameterized JSON message.
 *//*from   w ww.ja  v a2  s. c om*/
public static FancyMessage deserialize(String json) {
    JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
    JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
    FancyMessage returnVal = new FancyMessage();
    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 FancyMessage
                    // 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 - FancyMessages
                        // Recurse within this function to parse this as a translation replacement
                        component.translationReplacements.add(deserialize(object.toString()));
                    }
                }
            }
        }
        returnVal.messageParts.add(component);
    }
    return returnVal;
}

From source file:com.skysql.manager.api.SettingsValues.java

License:Open Source License

public SettingsValues deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException, NullPointerException {
    SettingsValues settingsValues = new SettingsValues();

    JsonElement jsonElement = json.getAsJsonObject().get("applicationproperty");
    if (jsonElement.isJsonNull()) {
        settingsValues.setValues(null);/*from   w  w  w.  j  a v  a  2s. co  m*/
    } else {
        JsonObject jsonObject = (JsonObject) jsonElement;
        Set<Entry<String, JsonElement>> set = jsonObject.entrySet();
        Iterator<Entry<String, JsonElement>> iter = set.iterator();
        if (iter.hasNext()) {
            Entry<String, JsonElement> entry = iter.next();
            String value = entry.getValue().getAsString();
            settingsValues.setValues(value.split(","));
        }
    }

    return settingsValues;
}

From source file:com.sldeditor.exportdata.esri.MXDParser.java

License:Open Source License

/**
 * Process fields.//from  ww  w  .j  ava 2 s. c  o  m
 *
 * @param layerName the layer name
 * @param dataSourcePropertiesElement the data source properties element
 * @return the data source properties
 */
private DataSourcePropertiesInterface processDataSource(String layerName,
        JsonElement dataSourcePropertiesElement) {
    Map<String, String> propertyMap = new LinkedHashMap<String, String>();

    if (dataSourcePropertiesElement != null) {
        JsonObject dsObj = dataSourcePropertiesElement.getAsJsonObject();

        JsonElement typeElement = dsObj.get(DatasourceKeys.TYPE);
        if (typeElement != null) {
            propertyMap.put(DatasourceKeys.TYPE, typeElement.getAsString());
        }

        JsonElement pathElement = dsObj.get(DatasourceKeys.PATH);
        if (pathElement != null) {
            propertyMap.put(DatasourceKeys.PATH, pathElement.getAsString());
        }

        JsonObject properties = dsObj.getAsJsonObject(DatasourceKeys.PROPERTIES);

        if (properties != null) {
            for (Map.Entry<String, JsonElement> field : properties.entrySet()) {
                propertyMap.put(field.getKey(), field.getValue().getAsString());
            }
        }
    }

    DataSourcePropertiesInterface dataSourceProperties = DataSourceManager.getInstance().convert(propertyMap);

    return dataSourceProperties;
}

From source file:com.smart.taxi.model.WebServiceModel.java

public static HttpAsyncTask getCabsAroundMe(final LatLng latLng, HttpResponseListener responseListener,
        HttpProgressListener httpProgressListener) {
    final String methodName = APIConstants.METHOD_GET_CABS_AROUND_ME;
    final String url = getCompleteURLForMethod(methodName);
    HttpAsyncTask httpAsyncTask = new HttpAsyncTask(responseListener, new HttpRequestListener() {

        @Override/* w w w .jav a2 s. c om*/
        public Object makeRequest(HttpAsyncTask httpAsyncTask) throws CustomHttpException {
            if (httpAsyncTask.isCancelled())
                return null;
            try {
                httpAsyncTask.updateProgress(1);
                List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                params.add(new BasicNameValuePair(APIConstants.KEY_USER_LAT, String.valueOf(latLng.latitude)));
                httpAsyncTask.updateProgress(2);
                params.add(
                        new BasicNameValuePair(APIConstants.KEY_USER_LONG, String.valueOf(latLng.longitude)));
                httpAsyncTask.updateProgress(3);

                String response = HttpRequestHelper2.httpPost(url, params);
                for (int i = 4; i <= 50; i++) {
                    httpAsyncTask.updateProgress(i);
                }
                httpAsyncTask.updateProgress(55);
                if (Utils.isEmptyOrNull(response)) {
                    throw new Exception();
                }
                httpAsyncTask.updateProgress(56);
                String responseMessage = getMessageFromResponseHeader(response);
                httpAsyncTask.updateProgress(57);
                int responseCode = getCodeFromResponseHeader(response);
                httpAsyncTask.updateProgress(58);
                httpAsyncTask.updateProgress(60);
                if (isErrorCode(responseCode)) {
                    throw new Exception(responseMessage);
                }
                httpAsyncTask.updateProgress(61);
                ArrayList<Cab> cabsList = new ArrayList<Cab>();
                JsonObject cabsObject = getJsonObjectFromBody(response, APIConstants.KEY_CABS);
                httpAsyncTask.updateProgress(70);
                int count = cabsObject.entrySet().size();
                for (Map.Entry<String, JsonElement> entry : cabsObject.entrySet()) {
                    JsonElement value = entry.getValue();
                    Cab cab = new Cab();
                    cab.deserializeFromJSON(value);
                    cabsList.add(cab);
                    int position = Integer.parseInt(entry.getKey());
                    httpAsyncTask.updateProgress(70 + (int) ((position / (float) count) * 30));
                }
                httpAsyncTask.updateProgress(100);
                if (Utils.isEmptyOrNull(cabsList))
                    throw new Exception("No Cabs found");
                return new CustomHttpResponse(cabsList, methodName, 200, responseMessage);
            } catch (Exception e) {
                e.printStackTrace();
                return new CustomHttpException(methodName, e.getMessage());
            }
        }
    }, httpProgressListener);
    return executeAsyncTask(httpAsyncTask);
}

From source file:com.smarttaxi.driver.BAL.Driver.java

public static ArrayList<Journey> parseHistory(JsonObject json) {
    ArrayList<Journey> list = new ArrayList<Journey>();
    String firstName = "", lastName = "", corporateName = "", pickFromAddress = "", pickFromTime = "",
            dropToAddress = "", dropToTime = "";
    String paymentType = "", paymentAmout = "", tipGiven = "";
    boolean taxIncluded = false;

    try {/*from w  ww  .  ja v  a 2s .co  m*/
        /****** JOURNEYS ****/
        for (Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            JsonElement jsonElement = entry.getValue();
            JsonObject journeyUsersObject = JsonHelper.getJsonObject(jsonElement.getAsJsonObject(),
                    "journey_users");
            // Applog.Debug("journeyUsersObject " + journeyUsersObject);

            /** JOURNEY_USERS **/
            for (Entry<String, JsonElement> journey : journeyUsersObject.getAsJsonObject().entrySet()) {
                JsonElement jsonJourneyElement = journey.getValue();

                pickFromTime = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "pickup_time");
                pickFromAddress = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(),
                        "pickup_door_address");
                dropToAddress = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(),
                        "dropOff_door_address");

                taxIncluded = Utils.isEmptyOrNull(
                        JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "extras")) ? false : true;
                dropToTime = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "dropOff_time");
                tipGiven = JsonHelper.getString(jsonJourneyElement.getAsJsonObject(), "tip_given");
                Applog.Debug("TRIP : Pick From " + pickFromAddress);

                JsonObject usersObject = JsonHelper.getJsonObject(jsonJourneyElement.getAsJsonObject(),
                        "users");

                /******* USERS *******/
                for (Entry<String, JsonElement> users : usersObject.entrySet()) {
                    JsonElement usersJsonElement = users.getValue();
                    firstName = JsonHelper.getString(usersJsonElement.getAsJsonObject(),
                            APIConstants.KEY_FIRST_NAME);
                    lastName = JsonHelper.getString(usersJsonElement.getAsJsonObject(),
                            APIConstants.KEY_LAST_NAME);
                    Applog.Debug("TRIP : firstName " + firstName);
                    /******* Coparate Users *******/
                    try {
                        JsonObject coparteUsersObject = JsonHelper
                                .getJsonObject(usersJsonElement.getAsJsonObject(), "corporate_users");
                        corporateName = JsonHelper.getString(coparteUsersObject, APIConstants.KEY_NAME);
                        Applog.Debug("TRIP : coparteUsersObject " + corporateName);
                    } catch (Exception e) {
                        corporateName = "";
                    }

                }
                /***** USERS END ******/

                /******* PAYMENT *******/
                JsonObject paymentObject = JsonHelper.getJsonObject(jsonJourneyElement.getAsJsonObject(),
                        "Payment");
                for (Entry<String, JsonElement> paymentEntry : paymentObject.entrySet()) {
                    JsonElement paymentJsonElement = paymentEntry.getValue();
                    paymentAmout = JsonHelper.getString(paymentJsonElement.getAsJsonObject(), "amount");
                    paymentType = JsonHelper.getString(paymentJsonElement.getAsJsonObject(), "payment_type");
                    Applog.Debug("TRIP : paymentAMount " + paymentAmout);
                }
            }

            Journey journey = new Journey();
            journey.setCorporateName(corporateName);
            journey.setDropToAddress(dropToAddress);
            journey.setDropToTime(dropToTime);
            journey.setFirstName(firstName);
            journey.setLastName(lastName);
            journey.setPaymentAmout(paymentAmout);
            journey.setExtras(taxIncluded);
            journey.setPaymentType(paymentType);
            journey.setPickFromAddress(pickFromAddress);
            journey.setPickFromTime(pickFromTime);
            journey.setTipGiven(tipGiven);
            list.add(journey);

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return list;
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java

License:Open Source License

private @CheckForNull Object toSimpleJavaType(JsonElement jsonValue) {
    if (jsonValue == null)
        return null; //VR
    Object value = null;//from   w  w w  . ja v  a 2s  . c o  m
    if (!jsonValue.isJsonNull()) {
        if (jsonValue.isJsonPrimitive()) {
            JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
            if (primitive.isBoolean()) {
                value = Boolean.valueOf(primitive.getAsBoolean());
            } else if (primitive.isNumber()) {
                value = Double.valueOf(primitive.getAsDouble());
            } else if (primitive.isString()) {
                value = primitive.getAsString();
            } else {
                throw UnexpectedException.forUnexpectedCodeBranchExecuted();
            }
        } else if (jsonValue.isJsonArray()) {
            //This simply does not work (?) 
            JsonArray array = jsonValue.getAsJsonArray();
            Object[] result = new Object[array.size()];
            for (int i = 0; i < array.size(); i++) {
                result[i] = toSimpleJavaType(array.get(i));
            }
            value = result;
        } else if (jsonValue.isJsonObject()) {
            //This simply does not work (?)
            //value = getGson().fromJson(jsonValue, Map.class );

            JsonObject obj = jsonValue.getAsJsonObject();
            Iterator<Entry<String, JsonElement>> properties = obj.entrySet().iterator();
            Map<String, Object> result = new HashMap<String, Object>();
            while (properties.hasNext()) {
                Entry<String, JsonElement> property = properties.next();
                JsonElement propertyValue = property.getValue();
                result.put(property.getKey(), toSimpleJavaType(propertyValue));
            }
            value = result;
        } else {
            throw UnexpectedException.forUnexpectedCodeBranchExecuted();
        }
    }

    return value;
}

From source file:com.sonie.web.util.HueUtil.java

License:Open Source License

public static Map<String, String> getScenesWithId(ApplicationConfiguration config) {
    RestTemplate restTemplate = new RestTemplate();
    Map<String, String> scenes = new HashMap<>();

    String url = "http://" + config.getHue().getIp() + "/api/" + config.getHue().getUser() + "/scenes";
    ResponseEntity<String> hueScenesResponse = restTemplate.exchange(url, HttpMethod.GET, null,
            new ParameterizedTypeReference<String>() {
            });//  w  ww.j  a v a  2  s . c o  m

    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(hueScenesResponse.getBody()).getAsJsonObject();

    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        scenes.put(entry.getKey(), entry.getValue().getAsJsonObject().get("name").toString());
    }

    return scenes;
}