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.haulmont.restapi.common.RestParseUtils.java

License:Apache License

public Map<String, String> parseParamsJson(String paramsJson) {
    Map<String, String> result = new LinkedHashMap<>();
    if (Strings.isNullOrEmpty(paramsJson))
        return result;

    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = jsonParser.parse(paramsJson).getAsJsonObject();

    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String paramName = entry.getKey();
        JsonElement paramValue = entry.getValue();
        if (paramValue.isJsonNull()) {
            result.put(paramName, null);
        } else if (paramValue.isJsonPrimitive()) {
            result.put(paramName, paramValue.getAsString());
        } else {/*from  w w w.j  a  v  a2s  .c om*/
            result.put(paramName, paramValue.toString());
        }
    }

    return result;
}

From source file:com.hbm.devices.jet.JetPeer.java

License:Open Source License

private JsonObject fillPath(Matcher matcher) {
    JsonObject path = new JsonObject();

    if ((matcher.contains != null && !matcher.contains.isEmpty())) {
        path.addProperty("contains", matcher.contains);

    }//  ww  w  .j  av  a  2s. c o  m

    if ((matcher.startsWith != null && !matcher.startsWith.isEmpty())) {
        path.addProperty("startsWith", matcher.startsWith);
    }

    if ((matcher.endsWith != null && !matcher.endsWith.isEmpty())) {
        path.addProperty("endsWith", matcher.endsWith);
    }

    if ((matcher.equals != null && !matcher.equals.isEmpty())) {
        path.addProperty("equals", matcher.equals);
    }

    if ((matcher.equalsNot != null && !matcher.equalsNot.isEmpty())) {
        path.addProperty("equalsNot", matcher.equalsNot);
    }

    if ((matcher.containsAllOf != null) && (matcher.containsAllOf.length > 0)) {
        JsonArray containsArray = new JsonArray();
        for (String element : matcher.containsAllOf) {
            containsArray.add(new JsonPrimitive(element));
        }

        path.add("containsAllOf", containsArray);
    }

    if ((path.entrySet() != null) && (path.entrySet().size() > 0)) {
        return path;
    } else {
        return null;
    }
}

From source file:com.headswilllol.mineflat.gui.GuiParser.java

License:Open Source License

private static GuiElement parseElement(String id, JsonObject json, Optional<GuiElement> parent) {
    GuiElement element = null; // only remains null if this element can't be parsed
    int height;/*from w  ww  .  j av a  2 s .c  o  m*/
    if (json.has("height")) {
        if (json.get("height").getAsString().endsWith("%")) {
            // height is defined as percentage of parent height
            height = (int) (Integer.parseInt(json.get("height").getAsString().replace("%", "")) / 100f
                    * (parent.isPresent() ? parent.get().getSize().getY() : Display.getHeight()));
        } else {
            // height is standard pixel count
            height = json.get("height").getAsInt();
        }
    } else {
        if (parent.isPresent()) {
            height = parent.get().getSize().getY(); // use parent element height
        } else {
            height = Display.getHeight(); // default to full window height
        }
    }
    if (height < 0)
        height = Display.getHeight() + height;

    int width;
    if (json.has("width")) {
        if (json.get("width").getAsString().endsWith("%")) {
            // width is defined as percentage of parent height
            width = (int) (Integer.parseInt(json.get("width").getAsString().replace("%", "")) / 100f
                    * (parent.isPresent() ? parent.get().getSize().getX() : Display.getWidth()));
        } else {
            // width is standard pixel count
            width = json.get("width").getAsInt();
        }
    } else if (json.has("type") && json.get("type").getAsString().equalsIgnoreCase("text")
            && json.has("text")) {
        width = GraphicsHandler.getStringLength(json.get("text").getAsString(), height);
    } else {
        if (parent.isPresent()) {
            width = parent.get().getSize().getX(); // use parent element width
        } else {
            width = Display.getWidth(); // default to full window width
        }
    }
    if (width < 0)
        width = Display.getWidth() + width;

    int x = 0; // default to x=0 (relative to parent)
    if (json.has("x")) {
        String jsonX = json.get("x").getAsString();
        if (jsonX.equalsIgnoreCase("center")) {
            x = Integer.MAX_VALUE;
        } else
            x = Integer.parseInt(jsonX);
    }
    if (x < 0) // position is relative to right
        x = (parent.isPresent() ? parent.get().getSize().getX() : Display.getWidth()) + x;

    int y = json.has("y") ? json.get("y").getAsInt() : 0; // if not present, default to y=0 (relative to parent)
    if (y < 0) // position is relative to bottom
        y = (parent.isPresent() ? parent.get().getSize().getY() : Display.getHeight()) + y;

    Vector4f color = json.has("color") ? MiscUtil.hexToRGBA(json.get("color").getAsString()) : // use defined color
            MiscUtil.hexToRGBA("#FFF0"); // default to white transparent

    String text = json.has("text") ? json.get("text").getAsString() : ""; // default to empty string

    Class<?> handlerClass = null;
    if (json.has("handlerClass")) {
        try {
            handlerClass = Class.forName(json.get("handlerClass").getAsString());
        } catch (ClassNotFoundException ex) {
            System.err.println("Cannot resolve handler class for element " + id + "!");
            ex.printStackTrace();
        }
    } else if (parent.isPresent())
        handlerClass = parent.get().getHandlerClass().isPresent() ? parent.get().getHandlerClass().get() : null;

    if (json.has("type")) {
        String type = json.get("type").getAsString();
        switch (type) { // check defined type
        case "text": // text element
            // instantiate the new TextElement
            element = new TextElement(id, new Vector2i(x, y), text, height,
                    json.has("shadow") && json.get("shadow").getAsBoolean());
            break;
        case "button": // button element
            Vector4f hover = MiscUtil.hexToRGBA(json.get("hoverColor").getAsString());
            if (handlerClass != null) {
                if (json.has("handlerMethod")) {
                    String mName = json.get("handlerMethod").getAsString();
                    JsonArray params = json.getAsJsonArray("handlerParams");
                    try {
                        Method m = handlerClass.getMethod(mName);
                        //TODO: params
                        element = new Button(id, new Vector2i(x, y), new Vector2i(width, height), text, color,
                                hover, m);
                    } catch (NoSuchMethodException ex) {
                        System.err.println("Failed to access handler method " + mName + " for element " + id);
                    }
                } else
                    System.err.println("No handler method for element " + id + "!");
            } else {
                System.err.println("No handler class for element " + id + "!");
            }
            break;
        case "panel": // container element
            element = new GuiElement(id, new Vector2i(x, y), new Vector2i(width, height), color);
            break;
        default:
            // unrecognized element, ignore it
            System.err.println("Unrecognized element type \"" + type + "\"");
            // default to container element
            element = new GuiElement(id, new Vector2i(x, y), new Vector2i(width, height), color);
            break;
        }
    } else {
        // default to container element
        element = new GuiElement(id, new Vector2i(x, y), new Vector2i(width, height), color);
    }
    if (element != null) {
        if (x == Integer.MAX_VALUE)
            elementsToCenter.add(element);
        element.setHandlerClass(handlerClass);
        for (Map.Entry<String, JsonElement> e : json.entrySet()) { // iterate subelements
            if (e.getValue().isJsonObject()) { // assert it's not a value for the current element
                // recursively parse subelements
                element.addChild(
                        parseElement(e.getKey(), e.getValue().getAsJsonObject(), Optional.of(element)));
            }
        }
    }
    return element;
}

From source file:com.headswilllol.mineflat.world.SaveManager.java

License:Open Source License

public static Chunk loadChunk(Level level, int chunk) {
    JsonObject jChunk = level.getWorld().getJson().getAsJsonObject("levels")
            .getAsJsonObject(Integer.toString(level.getIndex())).getAsJsonObject("chunks")
            .getAsJsonObject(Integer.toString(chunk));
    if (jChunk != null) {
        System.out.println("Loading chunk " + chunk);
        Biome biome = Biome.getById(jChunk.get("biome").toString());
        Chunk c = new Chunk(level, chunk, biome);
        for (JsonElement blockObj : jChunk.getAsJsonArray("blocks")) {
            JsonObject block = blockObj.getAsJsonObject();
            Material type = Material.valueOf(block.get("type").getAsString());
            if (type == null)
                type = Material.AIR;//from ww  w  .  j  a va2  s  . c o m
            int data = block.get("data") != null ? block.get("data").getAsInt() : 0;
            Block b = new Block(type, data,
                    new Location(level, Chunk.getWorldXFromChunkIndex(chunk, block.get("x").getAsLong()),
                            block.get("y").getAsLong()));
            JsonObject meta = (JsonObject) block.get("metadata");
            for (Map.Entry<String, JsonElement> e : meta.entrySet()) {
                JsonPrimitive prim = meta.get(e.getKey()).getAsJsonPrimitive();
                Object value;
                if (prim.isBoolean())
                    value = prim.getAsBoolean();
                else if (prim.isNumber())
                    value = prim.getAsNumber();
                else if (prim.isString())
                    value = prim.getAsString();
                else
                    value = prim.getAsCharacter();
                b.setMetadata(e.getKey(), value);
            }
            b.addToWorld();
        }
        for (Object entityObj : jChunk.get("entities").getAsJsonArray()) {
            JsonObject entity = (JsonObject) entityObj;
            EntityType type = EntityType.valueOf(entity.get("type").getAsString());
            float x = Chunk.getWorldXFromChunkIndex(c.getIndex(),
                    Float.valueOf(Double.toString(entity.get("x").getAsDouble())));
            float y = Float.valueOf(Double.toString(entity.get("y").getAsDouble()));
            float w = Float.valueOf(Double.toString(entity.get("w").getAsDouble()));
            float h = Float.valueOf(Double.toString(entity.get("h").getAsDouble()));
            Entity e;
            if (entity.has("living")) {
                if (entity.has("mob")) {
                    switch (type) {
                    case GHOST:
                        e = new Ghost(new Location(level, x, y));
                        break;
                    case SNAIL:
                        e = new Snail(new Location(level, x, y));
                        break;
                    default:
                        continue; // ignore it
                    }
                    ((Mob) e).setPlannedWalkDistance(entity.get("pwd").getAsFloat());
                    ((Mob) e).setActualWalkDistance(entity.get("awd").getAsFloat());
                    ((Mob) e).setLastX(entity.get("lx").getAsFloat());
                } else {
                    switch (type) {
                    case PLAYER:
                        e = new Player(new Location(level, x, y));
                        break;
                    case HUMAN:
                        e = new Human(new Location(level, x, y));
                        break;
                    default:
                        continue; // ignore it
                    }
                }
                ((Living) e).setFacingDirection(Direction.valueOf(entity.get("fd").getAsString()));
                ((Living) e).setJumping(entity.get("j").getAsBoolean());
            } else
                e = new Entity(type, new Location(level, x, y), w, h);
            e.getVelocity().setX(Float.valueOf(Double.toString(entity.get("xv").getAsDouble())));
            e.getVelocity().setY(Float.valueOf(Double.toString(entity.get("yv").getAsDouble())));
            level.addEntity(e);
            if (type == EntityType.PLAYER)
                Main.player = (Player) e;
        }
        c.updateLight();
        Chunk left = c.getLevel().getChunk(c.getIndex() == 1 ? -1 : c.getIndex() - 1);
        Chunk right = c.getLevel().getChunk(c.getIndex() == -1 ? 1 : c.getIndex() + 1);
        if (left != null) {
            for (int y = 0; y < c.getLevel().getWorld().getChunkHeight(); y++) {
                left.getBlock(c.getLevel().getWorld().getChunkLength() - 1, y).updateLight();
                VboUtil.updateChunkArray(c.getLevel(), left.getIndex());
            }
        }
        if (right != null) {
            for (int y = 0; y < c.getLevel().getWorld().getChunkHeight(); y++) {
                right.getBlock(0, y).updateLight();
                VboUtil.updateChunkArray(c.getLevel(), right.getIndex());
            }
        }
        System.gc(); //TODO: temporary fix until I have the motivation to find the memory leak
        return c;
    }
    return null;
}

From source file:com.helion3.prism.util.DataUtil.java

License:MIT License

/**
 * Build a DataView from provided JSON.//from ww  w  .  j av  a2s.co m
 * @param json JsonObject
 * @return DataView
 */
public static DataView dataViewFromJson(JsonObject json) {
    DataContainer data = new MemoryDataContainer();
    for (Entry<String, JsonElement> entry : json.entrySet()) {
        Optional<Object> value = jsonElementToObject(entry.getValue());
        if (value.isPresent()) {
            data.set(DataQuery.of(entry.getKey()), value.get());
        } else {
            Prism.getLogger().error(String.format("Failed to transform %s data.", entry.getKey()));
        }
    }

    return data;
}

From source file:com.helion3.safeguard.util.DataUtil.java

License:MIT License

/**
 * Convert JSON to a DataContainer./*from  w w w  .ja v a 2 s .  c  o m*/
 * @param json JsonObject
 * @return DataContainer
 */
public static DataContainer jsonToDataContainer(JsonObject json) {
    DataContainer result = new MemoryDataContainer();

    for (Entry<String, JsonElement> entry : json.entrySet()) {
        DataQuery keyQuery = DataQuery.of(entry.getKey());
        Object object = entry.getValue();

        if (object instanceof JsonObject) {
            result.set(keyQuery, jsonToDataContainer((JsonObject) object));
        } else if (object instanceof JsonArray) {
            JsonArray array = (JsonArray) object;
            Iterator<JsonElement> iterator = array.iterator();

            List<Object> list = new ArrayList<Object>();
            while (iterator.hasNext()) {
                Object child = iterator.next();

                if (child instanceof JsonPrimitive) {
                    JsonPrimitive primitive = (JsonPrimitive) child;

                    if (primitive.isString()) {
                        list.add(primitive.getAsString());
                    } else if (primitive.isNumber()) {
                        // @todo may be wrong format. how do we handle?
                        list.add(primitive.getAsInt());
                    } else if (primitive.isBoolean()) {
                        list.add(primitive.getAsBoolean());
                    } else {
                        SafeGuard.getLogger()
                                .error("Unhandled list JsonPrimitive data type: " + primitive.toString());
                    }
                }
            }

            result.set(keyQuery, list);
        } else {
            if (object instanceof JsonPrimitive) {
                JsonPrimitive primitive = (JsonPrimitive) object;

                if (primitive.isString()) {
                    result.set(keyQuery, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    // @todo may be wrong format. how do we handle?
                    result.set(keyQuery, primitive.getAsInt());
                } else if (primitive.isBoolean()) {
                    result.set(keyQuery, primitive.getAsBoolean());
                } else {
                    SafeGuard.getLogger().error("Unhandled JsonPrimitive data type: " + primitive.toString());
                }
            }
        }
    }

    return result;
}

From source file:com.hybris.datahub.service.impl.DefaultJsonService.java

License:Open Source License

private Map<String, String> convertJsonObject(final JsonObject jsonObject) {
    LOG.debug("Convert json object: " + jsonObject.toString());

    final Map<String, String> result = new HashMap<String, String>();
    for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        final JsonElement jsonElement = entry.getValue();
        result.put(entry.getKey(), convertJsonValue(jsonElement));
    }/*from  w w  w .ja v a 2 s.co  m*/
    return result;
}

From source file:com.ibasco.agql.protocols.valve.csgo.webapi.adapters.CsgoDatacenterStatusDeserializer.java

License:Open Source License

@Override
public List<CsgoDatacenterStatus> deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    log.debug("{}", json);
    JsonObject dataCenters = json.getAsJsonObject();
    List<CsgoDatacenterStatus> datacenterStatusList = new ArrayList<>();
    for (Map.Entry<String, JsonElement> entry : dataCenters.entrySet()) {
        String location = entry.getKey();
        CsgoDatacenterStatus status = context.deserialize(entry.getValue(), CsgoDatacenterStatus.class);
        status.setLocation(location);//from w  w w .  j  a  va  2  s .  c  om
        datacenterStatusList.add(status);
    }
    return datacenterStatusList;
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.adapters.SteamAssetClassInfoMapDeserializer.java

License:Open Source License

@Override
public Map<String, SteamAssetClassInfo> deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    Map<String, SteamAssetClassInfo> map = new HashMap<>();
    JsonObject jObject = json.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : jObject.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        //Only process entries that are of type object
        if (value.isJsonObject()) {
            map.put(key, context.deserialize(value, SteamAssetClassInfo.class));
        }//from  w  w w  .j a  v  a2 s  .co  m
    }
    log.debug("Finished populating map. Total Map Size: {}", map.size());
    return map;
}

From source file:com.ibm.common.activitystreams.internal.ASObjectAdapter.java

License:Apache License

/**
 * Method deserialize.// w  w  w  .j av  a 2s . c o  m
 * @param element JsonElement
 * @param type Type
 * @param context JsonDeserializationContext
 * @return ASObject 
 * @throws JsonParseException
 * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) 
 **/
public final ASObject deserialize(JsonElement element, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject obj = (JsonObject) element;
    ASObject.AbstractBuilder<?, ?> builder = null;
    Model propMap = null;
    TypeValue tv = null;

    if (knowsType(type)) {
        builder = builderFor(type);
        propMap = modelFor(type);
    } else {
        if (obj.has("objectType")) {
            tv = context.deserialize(obj.get("objectType"), TypeValue.class);
            @SuppressWarnings("rawtypes")
            Class<? extends ASObject.AbstractBuilder> _class = schema.builderForObjectTypeOrClass(tv.id(),
                    (Class) type);
            if (_class != null) {
                propMap = schema.forObjectClassOrType(_class, tv.id());
                if (!_class.isInterface()) {
                    try {
                        builder = _class.getConstructor(String.class).newInstance(tv.id());
                    } catch (Throwable t) {
                        try {
                            builder = _class.newInstance();
                            builder.set("objectType", tv);
                        } catch (Throwable t2) {
                            builder = Makers.object(tv);
                        }
                    }
                } else
                    builder = Makers.object(tv);
            } else {
                builder = Makers.object(tv);
                propMap = schema.forObjectClassOrType(ASObject.Builder.class, tv.id());
            }
        } else {
            if (obj.has("verb") && (obj.has("actor") || obj.has("object") || obj.has("target"))) {
                builder = activity();
                propMap = schema.forObjectClassOrType(Activity.Builder.class, "activity");
            } else if (obj.has("items")) {
                builder = collection();
                propMap = schema.forObjectClassOrType(Collection.Builder.class, "collection");
            } else {
                @SuppressWarnings("rawtypes")
                Class<? extends ASObject.AbstractBuilder> _class = schema.builderFor((Class) type);
                if (_class != null) {
                    if (!_class.isInterface()) {
                        try {
                            builder = _class.newInstance();
                        } catch (Throwable t) {
                            builder = object();
                        }
                    } else
                        builder = object();
                }
                if (builder == null)
                    builder = object(); // anonymous
                propMap = schema.forObjectClass(builder.getClass());
                propMap = propMap != null ? propMap : schema.forObjectClass(ASObject.Builder.class);
            }
        }
    }

    for (Entry<String, JsonElement> entry : obj.entrySet()) {
        String name = entry.getKey();
        if (name.equalsIgnoreCase("objectType"))
            continue;
        Class<?> _class = propMap.get(name);
        JsonElement val = entry.getValue();
        if (val.isJsonPrimitive())
            builder.set(name, _class != null ? context.deserialize(val, _class)
                    : primConverter.convert(val.getAsJsonPrimitive()));
        else if (val.isJsonArray()) {
            builder.set(name,
                    LinkValue.class.isAssignableFrom(_class != null ? _class : Object.class)
                            ? context.deserialize(val, LinkValue.class)
                            : convert(val.getAsJsonArray(), _class, context, builder()));
        } else if (val.isJsonObject())
            builder.set(name, context.deserialize(val, propMap.has(name) ? propMap.get(name) : ASObject.class));
    }
    return builder.get();

}