Example usage for com.google.gson JsonElement getAsJsonObject

List of usage examples for com.google.gson JsonElement getAsJsonObject

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonObject.

Prototype

public JsonObject getAsJsonObject() 

Source Link

Document

convenience method to get this element as a JsonObject .

Usage

From source file:blusunrize.immersiveengineering.client.models.multilayer.MultiLayerModel.java

@Nonnull
@Override//from  w  w w . j  a  va  2  s.  c  om
public IModel process(ImmutableMap<String, String> customData) {
    Map<BlockRenderLayer, List<ModelData>> newSubs = new HashMap<>();
    JsonParser parser = new JsonParser();
    Map<String, String> unused = new HashMap<>();
    for (String layerStr : customData.keySet())
        if (LAYERS_BY_NAME.containsKey(layerStr)) {

            BlockRenderLayer layer = LAYERS_BY_NAME.get(layerStr);
            JsonElement ele = parser.parse(customData.get(layerStr));
            if (ele.isJsonObject()) {
                ModelData data = ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                        ImmutableMap.of());
                newSubs.put(layer, ImmutableList.of(data));
            } else if (ele.isJsonArray()) {
                JsonArray array = ele.getAsJsonArray();
                List<ModelData> models = new ArrayList<>();
                for (JsonElement subEle : array)
                    if (subEle.isJsonObject())
                        models.add(ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                                ImmutableMap.of()));
                newSubs.put(layer, models);
            }
        } else
            unused.put(layerStr, customData.get(layerStr));
    JsonObject unusedJson = ModelData.asJsonObject(unused);
    for (Entry<BlockRenderLayer, List<ModelData>> entry : newSubs.entrySet())
        for (ModelData d : entry.getValue())
            for (Entry<String, JsonElement> entryJ : unusedJson.entrySet())
                if (!d.data.has(entryJ.getKey()))
                    d.data.add(entryJ.getKey(), entryJ.getValue());
    if (!newSubs.equals(subModels))
        return new MultiLayerModel(newSubs);
    return this;
}

From source file:bot.parser.TelegramUpdateDeserializer.java

@Override
public Update deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {

    Update u = new Update();

    u.setUpdate_id(je.getAsJsonObject().get("update_id").getAsLong());
    // Get the "content" element from the parsed JSON
    JsonElement message = je.getAsJsonObject().get("message");
    Message m = new Message();

    m.setMessage_id(message.getAsJsonObject().get("message_id").getAsInt());
    m.setDate(message.getAsJsonObject().get("date").getAsLong());
    m.setText(message.getAsJsonObject().get("text").getAsString());

    User f = new User();

    JsonElement from = message.getAsJsonObject().get("from");

    f.setFirst_name(from.getAsJsonObject().get("first_name").getAsString());
    f.setLast_name(from.getAsJsonObject().get("last_name").getAsString());
    f.setId(from.getAsJsonObject().get("id").getAsInt());

    m.setFrom(f);//from ww  w.j av a  2s  .  c o m

    Chat c = new Chat();

    JsonElement chat = message.getAsJsonObject().get("chat");

    c.setFirst_name(chat.getAsJsonObject().get("first_name").getAsString());
    c.setLast_name(chat.getAsJsonObject().get("last_name").getAsString());
    c.setId(chat.getAsJsonObject().get("id").getAsLong());
    c.setType(chat.getAsJsonObject().get("type").getAsString());

    m.setChat(c);

    u.setMessage(m);

    // Deserialize it. You use a new instance of Gson to avoid infinite recursion
    // to this deserializer
    return u;

}

From source file:br.com.caelum.vraptor.serialization.gson.GsonDeserialization.java

License:Open Source License

@Override
public Object[] deserialize(InputStream inputStream, ControllerMethod method) {
    Class<?>[] types = getTypes(method);

    if (types.length == 0) {
        throw new IllegalArgumentException(
                "Methods that consumes representations must receive just one argument");
    }//  ww w. j  a v  a  2  s .c  o m

    Gson gson = builder.create();

    final Parameter[] parameterNames = paramNameProvider.parametersFor(method.getMethod());
    final Object[] values = new Object[parameterNames.length];
    final Deserializee deserializee = deserializeeInstance.get();

    try {
        String content = getContentOfStream(inputStream);
        logger.debug("json retrieved: {}", content);

        if (!isNullOrEmpty(content)) {
            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(content);
            if (jsonElement.isJsonObject()) {
                JsonObject root = jsonElement.getAsJsonObject();

                deserializee.setWithoutRoot(isWithoutRoot(parameterNames, root));

                for (Class<? extends DeserializerConfig> option : method.getMethod()
                        .getAnnotation(Consumes.class).options()) {
                    DeserializerConfig config = container.instanceFor(option);
                    config.config(deserializee);
                }

                for (int i = 0; i < types.length; i++) {
                    Parameter parameter = parameterNames[i];
                    JsonElement node = root.get(parameter.getName());

                    if (deserializee.isWithoutRoot()) {
                        values[i] = gson.fromJson(root, fallbackTo(parameter.getParameterizedType(), types[i]));
                        logger.info("json without root deserialized");
                        break;

                    } else if (node != null) {
                        if (node.isJsonArray()) {
                            JsonArray jsonArray = node.getAsJsonArray();
                            Type type = parameter.getParameterizedType();
                            if (type instanceof ParameterizedType) {
                                values[i] = gson.fromJson(jsonArray, type);
                            } else {
                                values[i] = gson.fromJson(jsonArray, types[i]);
                            }
                        } else {
                            values[i] = gson.fromJson(node, types[i]);
                        }
                    }
                }
            } else if (jsonElement.isJsonArray()) {
                if ((parameterNames.length != 1)
                        || (!(parameterNames[0].getParameterizedType() instanceof ParameterizedType)))
                    throw new IllegalArgumentException(
                            "Methods that consumes an array representation must receive only just one collection generic typed argument");

                JsonArray jsonArray = jsonElement.getAsJsonArray();
                values[0] = gson.fromJson(jsonArray, parameterNames[0].getParameterizedType());
            } else {
                throw new IllegalArgumentException("This is an invalid or not supported json content");
            }
        }
    } catch (Exception e) {
        throw new ResultException("Unable to deserialize data", e);
    }

    logger.debug("json deserialized: {}", (Object) values);
    return values;
}

From source file:br.com.rednetsolucoes.merendaescolar.serviceimpl.MerendaEscolaServiceImpl.java

@Override
public List<MerendaEscola> listarEscolas() {
    String uri = "http://localhost:8080/webresources/escolaservice";

    WebTarget webTarget = ClientBuilder.newClient().target(uri);
    String entity = webTarget.request().get().readEntity(String.class);

    List<MerendaEscola> escolas = new ArrayList<>();

    JsonParser parser = new JsonParser();
    JsonArray jsonArray = parser.parse(entity).getAsJsonArray();
    for (JsonElement j : jsonArray) {
        String nomeEscola = j.getAsJsonObject().get("nome").toString();
        long idEscola = j.getAsJsonObject().get("id").getAsLong();

        escolas.add(new MerendaEscola(new MerendaEstoque(), nomeEscola, idEscola));
    }//ww w.j a v  a2  s . c  o m

    return escolas;
}

From source file:br.com.rednetsolucoes.merendaescolar2.serviceimpl.EscolaEstoqueServiceImpl.java

@Override
public List<EscolaEstoque> listarEscolas() {
    String uri = "http://localhost:8080/webresources/escolaservice";

    WebTarget webTarget = ClientBuilder.newClient().target(uri);
    String entity = webTarget.request().get().readEntity(String.class);

    List<EscolaEstoque> escolas = new ArrayList<>();

    JsonParser parser = new JsonParser();
    JsonArray jsonArray = parser.parse(entity).getAsJsonArray();
    for (JsonElement j : jsonArray) {
        String nomeEscola = j.getAsJsonObject().get("nome").toString();
        long idEscola = j.getAsJsonObject().get("id").getAsLong();

        escolas.add(new EscolaEstoque(nomeEscola, idEscola, new ArrayList()));
    }//from w w  w .j  av  a 2s  .  com

    return escolas;
}

From source file:br.mack.api.Marvel.java

public static void main(String[] args) {
    //Criao de um timestamp
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhhmmss");
    String ts = sdf.format(date);

    //Criao do HASH
    String hashStr = MD5(ts + privatekey + apikey);
    String uri;/*  w  ww . j a  v a2 s .co m*/
    String name = "Captain%20America";
    //url de consulta
    uri = urlbase + "?nameStartsWith=" + name + "&ts=" + ts + "&apikey=" + apikey + "&hash=" + hashStr;

    try {
        CloseableHttpClient cliente = HttpClients.createDefault();

        //HttpHost proxy = new HttpHost("172.16.0.10", 3128, "http");
        //RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet(uri);
        //httpget.setConfig(config);
        HttpResponse response = cliente.execute(httpget);
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        //Header[] h = (Header[]) response.getAllHeaders();

        /*for (Header head : h) {
        System.out.println(head.getValue());
        }*/
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder out = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
            //System.out.println(out.toString());
            reader.close();
            instream.close();
            JsonParser parser = new JsonParser();

            // find character's comics
            JsonElement comicResultElement = parser.parse(out.toString());
            JsonObject comicDataWrapper = comicResultElement.getAsJsonObject();
            JsonObject data = (JsonObject) comicDataWrapper.get("data");
            JsonArray results = data.get("results").getAsJsonArray();

            System.out.println(((JsonObject) results.get(0)).get("thumbnail"));

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

}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * Turns the device belongs to someone. When a device is created in
 * Meshblu, it is an orphan device. In other words, everyone can made any
 * changes on this device. After claim a device, only the
 * owner can delete or update it.// w  w  w . jav a 2  s  .co  m
 * Note: In Meshblu, the owner for one device IS another device.
 *
 * @param device         the identifier of device (uuid)
 * @param callbackResult Callback for this method
 * @throws KnotException
 * @throws SocketNotConnected <p>
 *                            Check the reference on @see <a https://meshblu-socketio.readme.io/docs/unregister</a>
 */
public <T extends AbstractThingDevice> void deleteDevice(final T device, final Event<T> callbackResult)
        throws SocketNotConnected {

    if (isSocketRegistered() && isSocketConnected() && device != null) {
        JSONObject deviceToDelete = getNecessaryDeviceInformation(device);

        if (deviceToDelete != null) {
            mSocket.emit(EVENT_UNREGISTER_DEVICE, deviceToDelete, new Ack() {
                @Override
                public void call(Object... args) {
                    //Get First element of the array
                    if (args.length > 0 && args[FIRST_EVENT_RECEIVED] != null) {
                        JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString());
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.get(ERROR) != null) {
                            callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                        } else if (jsonObject.get(FROMUUID) != null) {
                            callbackResult.onEventFinish(device);
                        } else {
                            callbackResult.onEventError(new KnotException("Unknown error"));
                        }

                    } else {
                        callbackResult.onEventError(new KnotException("Failed to delete file"));
                    }

                }
            });
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }
}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * Update an existent device/*from www  .  j a  v a2  s .  c om*/
 *
 * @param device         the identifier of device (uuid)
 * @param callbackResult Callback for this method
 * @throws KnotException
 * @throws SocketNotConnected
 * @throws InvalidParametersException <p>
 *                                    Check the reference on @see <a https://meshblu-socketio.readme.io/docs/update</a>
 */
public <T extends AbstractThingDevice> void updateDevice(final T device, final Event<T> callbackResult)
        throws SocketNotConnected, InvalidParametersException {

    if (isSocketConnected() && isSocketRegistered()) {
        if (device != null && callbackResult != null) {
            String json = mGson.toJson(device);

            JSONObject deviceToUpdate = null;
            try {
                deviceToUpdate = new JSONObject(json);
            } catch (JSONException e) {
                throw new InvalidParametersException("Invalid parameters. Please, check your device object");
            }

            if (deviceToUpdate != null) {

                mSocket.emit(EVENT_UPDATE_DEVICE, deviceToUpdate, new Ack() {
                    @Override
                    public void call(Object... args) {
                        //Get First element of the array
                        if (args.length > 0 && args[FIRST_EVENT_RECEIVED] != null) {
                            JsonElement jsonElement = new JsonParser()
                                    .parse(args[FIRST_EVENT_RECEIVED].toString());
                            JsonObject jsonObject = jsonElement.getAsJsonObject();
                            if (jsonObject.get(ERROR) != null) {
                                callbackResult
                                        .onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                            } else {
                                T result = (T) mGson.fromJson(args[FIRST_EVENT_RECEIVED].toString(),
                                        device.getClass());
                                callbackResult.onEventFinish(result);
                            }

                        } else {
                            callbackResult.onEventError(new KnotException("Failed to update file"));
                        }
                    }
                });
            }
        } else {
            throw new InvalidParametersException("Invalid parameters");
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }
}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * Method used to claim a specif device;
 *
 * @param device         device Wanted/* w  w w . j av  a 2s.co m*/
 * @param callbackResult Callback for this method
 * @throws SocketNotConnected
 * @throws InvalidParametersException
 * @throws JSONException
 */
public <T extends AbstractThingDevice> void claimDevice(final T device, final Event<Boolean> callbackResult)
        throws SocketNotConnected, InvalidParametersException, JSONException {

    if (isSocketConnected() && isSocketRegistered()) {
        if (device != null && callbackResult != null) {
            JSONObject uuidDevice = new JSONObject();
            uuidDevice.put(UUID, device);

            mSocket.emit(EVENT_CLAIM_DEVICE, uuidDevice, new Ack() {
                @Override
                public void call(Object... args) {
                    if (args != null && args.length > 0) {
                        JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString());
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) {
                            callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                        } else {
                            callbackResult.onEventFinish(true);
                        }
                    } else {
                        callbackResult.onEventError(new KnotException("Error in reading the result"));
                    }
                }
            });
        } else {
            throw new InvalidParametersException("Invalid parameters");
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }

}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * This method returns a instance of the device
 *
 * @param typeClass      The specific genericized type of src.
 * @param uuid           The device identification to find a device on server
 * @param callbackResult Callback for this method
 * @param <T>            the type of the desired object
 * @throws JSONException//from  ww w. j a  v a  2s  . co  m
 */
public <T extends AbstractThingDevice> void getDevice(final T typeClass, String uuid,
        final Event<T> callbackResult) throws JSONException, InvalidParametersException, SocketNotConnected {

    if (isSocketConnected() && isSocketRegistered()) {
        if (typeClass != null && callbackResult != null && uuid != null) {

            JSONObject uuidDevice = new JSONObject();
            uuidDevice.put(UUID, uuid);

            mSocket.emit(EVENT_GET_DEVICE, uuidDevice, new Ack() {
                @Override
                public void call(Object... args) {

                    if (args != null && args.length > 0) {

                        JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString());
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) {
                            callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                        } else if (jsonObject.get(FROM) != null) {
                            JsonObject json = jsonObject.get(DEVICE).getAsJsonObject();
                            try {
                                T result = (T) mGson.fromJson(json.toString(), typeClass.getClass());
                                callbackResult.onEventFinish(result);
                            } catch (Exception e) {
                                callbackResult.onEventError(new KnotException("Error in reading the result"));
                            }
                        } else {
                            callbackResult.onEventError(new KnotException("Unknown error"));
                        }
                    } else {
                        callbackResult.onEventError(new KnotException("Error in reading the result"));
                    }
                }
            });

        } else {
            throw new InvalidParametersException("Invalid parameters");
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }

}