Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsString.

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

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

License:Open Source License

private void handleStateOrMethodCallbacks(JsonObject object) {
    try {/*from  w  w w.  j  a  v  a2 s  . com*/
        JsonPrimitive method = object.getAsJsonPrimitive("method");
        if (method == null) {
            throw new JsonRpcException(JsonRpcException.METHOD_NOT_FOUND, "no method given");
        }

        String path = method.getAsString();
        if ((path == null) || (path.length() == 0)) {
            throw new JsonRpcException(JsonRpcException.METHOD_NOT_FOUND, "method is not a string or integer");
        }

        boolean stateHandled = handleStateCallback(object, path);
        if (!stateHandled) {
            handleMethod(object, path);
        }
    } catch (JsonRpcException e) {
        sendResponse(object, e.getJson());
    }
}

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 www  . ja  v  a  2  s. c  om
            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.heartbuffer.pipette.json.FilterConfigJsonAdapter.java

License:Open Source License

@Override
public FilterConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive primitive = (JsonPrimitive) jsonObject.get(TYPE_FIELD);
    String filterType = primitive.getAsString();

    Class<?> clazz = null;//from  w w w.jav  a 2  s  .  c om

    switch (filterType) {
    case AddTimestampFilter.TYPE:
        clazz = AddTimestampFilterConfig.class;
        break;
    case EsDetermineDocumentDataFilter.TYPE:
        clazz = EsDetermineDocumentDataFilterConfig.class;
        break;
    case NDiffFilter.TYPE:
        //TODO: Add NDiffFilterConfig
        break;
    default:
        throw new JsonParseException("No such filter of type '" + filterType + "'");
    }

    return context.deserialize(jsonObject, clazz);
}

From source file:com.heartbuffer.pipette.json.InputConfigJsonAdapter.java

License:Open Source License

@Override
public InputConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive primitive = (JsonPrimitive) jsonObject.get(TYPE_FIELD);
    String inputType = primitive.getAsString();

    Class<?> clazz = null;//  www .j a v  a  2s  .c o  m

    switch (inputType) {
    case FileInput.TYPE:
        clazz = FileInputConfig.class;
        break;
    default:
        throw new JsonParseException("No such input of type '" + inputType + "'");
    }

    return context.deserialize(jsonObject, clazz);
}

From source file:com.heartbuffer.pipette.json.OutputConfigJsonAdapter.java

License:Open Source License

@Override
public OutputConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive primitive = (JsonPrimitive) jsonObject.get(TYPE_FIELD);
    String outputType = primitive.getAsString();

    Class<?> clazz = null;//  www .ja v  a  2  s .co  m

    switch (outputType) {
    case FileOutput.TYPE:
        //TODO: Add FileOutputConfig
        break;
    case ElasticsearchTransportOutput.TYPE:
        clazz = ElasticsearchTransportOutputConfig.class;
        break;
    case ElasticsearchHttpOutput.TYPE:
        clazz = ElasticsearchHttpOutputConfig.class;
        break;
    default:
        throw new JsonParseException("No such output of type '" + outputType + "'");
    }

    return context.deserialize(jsonObject, clazz);
}

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

License:MIT License

/**
 * Attempts to convert a JsonElement to an a known type.
 *
 * @param element JsonElement/*from  w  w w  .  j  av  a  2  s.  co m*/
 * @return Optional<Object>
 */
private static Optional<Object> jsonElementToObject(JsonElement element) {
    Object result = null;

    if (element.isJsonObject()) {
        result = dataViewFromJson(element.getAsJsonObject());
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive prim = element.getAsJsonPrimitive();

        if (prim.isBoolean()) {
            result = prim.getAsBoolean();
        } else if (prim.isNumber()) {
            result = prim.getAsNumber().intValue();
        } else if (prim.isString()) {
            result = prim.getAsString();
        }
    } else if (element.isJsonArray()) {
        List<Object> list = new ArrayList<Object>();
        JsonArray arr = element.getAsJsonArray();
        arr.forEach(new Consumer<JsonElement>() {
            @Override
            public void accept(JsonElement t) {
                Optional<Object> translated = jsonElementToObject(t);
                if (translated.isPresent()) {
                    list.add(translated.get());
                }
            }
        });

        result = list;
    }

    return Optional.ofNullable(result);
}

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

License:MIT License

/**
 * Convert JSON to a DataContainer.//from   w w w. j av  a 2s  .  c om
 * @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.hi3project.dandelion.fio.repository.comm.codec.json.JsonFIORepositoryProtocolCodec.java

License:Open Source License

@Override
public RequestResponseMessage decodeRequestResponseMessage(String data) throws MessageCodeDecodeErrorException {

    JsonParser jsonParser = new JsonParser();

    JsonElement msgJson = jsonParser.parse(data);

    JsonPrimitive typeJson = msgJson.getAsJsonObject().getAsJsonPrimitive("type");

    String typeStr = typeJson.getAsString();

    if (typeStr.equals(FIORepositoryMessageType.FIOEntryResponse.toString())) {
        return decodeFIOEntryResponse(msgJson);
    } else if (typeStr.equals(FIORepositoryMessageType.DeregisterFIOAction.toString())) {
        return decodeDeregisterFIOAction(msgJson);
    } else if (typeStr.equals(FIORepositoryMessageType.RegisterFIOAction.toString())) {
        return decodeRegisterFIOAction(msgJson);
    } else if (typeStr.equals(FIORepositoryMessageType.FindFIOByIdAction.toString())) {
        return decodeFindFIOByIdAction(msgJson);
    } else if (typeStr.equals(FIORepositoryMessageType.QueryFIOByDistanceAction.toString())) {
        return decodeQueryFIOsByDistanceAction(msgJson);
    } else if (typeStr.equals(FIORepositoryMessageType.FIOQueryReponse.toString())) {
        return decodeFIOQueryResponse(msgJson);
    } else {/*from   w  ww . ja  va2  s  . co  m*/
        throw new MessageCodeDecodeErrorException("Unsupoprted message type.");
    }

}

From source file:com.hi3project.dandelion.gip.codec.json.JSONGIPCodec.java

License:Open Source License

private String jsonValueAsString(JsonElement value) throws GIPEventCodeDecodeErrorException {

    JsonPrimitive primitive = value.getAsJsonPrimitive();

    if (primitive.isString()) {
        return primitive.getAsString();
    } else if (primitive.isBoolean()) {
        return (Boolean.toString(primitive.getAsBoolean()));
    } else if (primitive.isNumber()) {
        return (Double.toString(primitive.getAsDouble()));
    } else {// w ww.  j a v a  2s. c  o  m
        throw new GIPEventCodeDecodeErrorException("", "Unable to decode JsonValue.");
    }

}

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

License:Apache License

/**
 * Method deserialize.//from  ww  w .  j av a 2 s .  co  m
 * @param json JsonElement
 * @param typeOfT Type
 * @param context JsonDeserializationContext
 * @return E
 * @throws JsonParseException
 * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)
 */
public E deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    checkArgument(json.isJsonPrimitive());
    JsonPrimitive jp = json.getAsJsonPrimitive();
    checkArgument(jp.isString());
    return des.convert(jp.getAsString());
}