Example usage for com.google.gson JsonObject get

List of usage examples for com.google.gson JsonObject get

Introduction

In this page you can find the example usage for com.google.gson JsonObject get.

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:bean.EJBean.java

License:Open Source License

public Edificio getEdificio(String id) {

    client = ClientBuilder.newClient();//w w w  . ja  v  a  2 s  . c  o  m
    String edificio = client.target(baseURI).path("edificios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Edificio> deserializer = new JsonDeserializer<Edificio>() {

        @Override
        public Edificio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();

            Edificio e = new Edificio();

            e.setIdedificio(jsonObject.get("idedificio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("direccion")) {
                e.setDireccion(jsonObject.get("direccion").getAsString());
            }
            if (jsonObject.has("telefono")) {
                e.setTelefono(jsonObject.get("telefono").getAsString());
            }
            if (jsonObject.has("enlace")) {
                e.setEnlace(jsonObject.get("enlace").getAsString());
            }
            e.setXano(jsonObject.get("xano").getAsString());
            e.setTopleft(jsonObject.get("topleft").getAsString());
            e.setTopright(jsonObject.get("topright").getAsString());
            e.setBottomleft(jsonObject.get("bottomleft").getAsString());

            // System.out.println("Deserializer: Edi Obj: "+e.toString());

            List<Usuario> lu = new ArrayList<Usuario>();
            JsonArray usuariosArray = jsonObject.getAsJsonArray("usuarios");
            for (JsonElement usuario : usuariosArray) {
                Usuario u = new Usuario();
                JsonObject usuarioObj = usuario.getAsJsonObject();
                u.setUsuario(usuarioObj.get("usuario").getAsString());
                lu.add(u);
            }
            // System.out.println("Deserializer: usu Obj: "+e.toString());

            e.setUsuarios(lu);
            // System.out.println("Deserializer: usu Obj: " + e.getUsuarios().size());
            List<Plano> lp = new ArrayList<Plano>();
            JsonArray planoArray = jsonObject.getAsJsonArray("planos");
            for (JsonElement plano : planoArray) {
                Plano p = new Plano();
                PlanoPK pk = new PlanoPK();
                JsonObject planoObj = plano.getAsJsonObject();
                pk.setIdedificio(e.getIdedificio());
                pk.setIdplano(planoObj.get("idplano").getAsString());
                p.setId(pk);
                p.setEnlace(planoObj.get("enlace").getAsString());
                p.setNivel(planoObj.get("nivel").getAsInt());
                Edificio edAux = new Edificio();
                edAux.setIdedificio(edAux.getIdedificio());
                p.setEdificio(edAux);

                lp.add(p);
            }

            e.setPlanos(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Edificio.class, deserializer);

    System.out.println("GSON" + edificio);

    Gson customGson = gsonBuilder.create();
    Edificio jsonToEdificio = customGson.fromJson(edificio, Edificio.class);
    System.out.print("Size users EJB: " + jsonToEdificio.getUsuarios().size());

    return jsonToEdificio;
}

From source file:bean.EJBean.java

License:Open Source License

public Espacio getEspacio(String id) {
    client = ClientBuilder.newClient();//from w  w w . j  ava 2s  .  c o  m
    String espacio = client.target(baseURI).path("espacios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    //      System.out.println(espacio);

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

        @Override
        public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();

            Espacio e = new Espacio();

            e.setIdespacio(jsonObject.get("idespacio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("bloque")) {
                e.setBloque(jsonObject.get("bloque").getAsString());
            }
            if (jsonObject.has("piso")) {
                e.setPiso(jsonObject.get("piso").getAsInt());
            }
            if (jsonObject.has("tipo")) {
                e.setTipo(jsonObject.get("tipo").getAsString());
            }
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());
            if (jsonObject.has("boundingbox")) {
                e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            }

            // System.out.println("Deserializer: Edi Obj: "+e.toString());
            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());

            e.setEdificio(edificio);

            List<Panorama> lp = new ArrayList<Panorama>();
            JsonArray panoArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement pano : panoArray) {
                Panorama p = new Panorama();
                JsonObject panoObj = pano.getAsJsonObject();
                p.setIdpanorama(panoObj.get("idpanorama").getAsString());
                p.setEnlace(panoObj.get("enlace").getAsString());
                lp.add(p);
            }

            e.setPanoramas(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            if (jsonObject.has("profesores")) {
                List<Profesor> lprof = new ArrayList<Profesor>();
                JsonArray profArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement prof : profArray) {
                    Profesor p = new Profesor();
                    JsonObject profObj = prof.getAsJsonObject();
                    p.setIdprofesor(profObj.get("idprofesor").getAsString());
                    p.setUsuario(profObj.get("usuario").getAsString());
                    p.setVisibilidad(profObj.get("visibilidad").getAsBoolean());

                    lprof.add(p);
                }

                e.setProfesores(lprof);
            }

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    // System.out.println("GSON"+espacio);

    Gson customGson = gsonBuilder.create();
    Espacio jsonToEspacio = customGson.fromJson(espacio, Espacio.class);

    return jsonToEspacio;
}

From source file:bean.EJBean.java

License:Open Source License

public List<Espacio> getEspaciosFromEdificio(String id) {

    client = ClientBuilder.newClient();/*w  w  w  . j a  v a2s. c o  m*/
    String espaciosJSON = client.target(baseURI).path("edificios").path(id).path("espacios")
            .request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

        @Override
        public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            JsonObject jsonObject = json.getAsJsonObject();

            Espacio e = new Espacio();

            // System.out.println("HOLA "+jsonObject.get("bloque").getAsString());

            e.setIdespacio(jsonObject.get("idespacio").getAsString());
            e.setNombrees(jsonObject.get("nombrees").getAsString());
            // e.setNombreen(jsonObject.get("nombreen").getAsString());
            // e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            e.setBloque(jsonObject.get("bloque").getAsString());
            e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            e.setPiso(jsonObject.get("piso").getAsInt());
            e.setTipo(jsonObject.get("tipo").getAsString());
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());
            e.setCoordenada(coordenada);

            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());
            /*
             * edificio.setNombrees(edificioObj.get("nombrees").getAsString());
             * edificio.setNombreen(edificioObj.get("nombreen").getAsString());
             * edificio.setNombrevl(edificioObj.get("nombrevl").getAsString());
             * edificio.setEnlace(edificioObj.get("enlace").getAsString());
             * edificio.setXano(edificioObj.get("xano").getAsString());
             * edificio.setTopleft(edificioObj.get("topleft").getAsString());
             * edificio.setTopright(edificioObj.get("topright").getAsString());
             * edificio.setBottomleft(edificioObj.get("bottomleft").getAsString());
             */
            e.setEdificio(edificio);

            List<Panorama> lu = new ArrayList<Panorama>();
            JsonArray panoramaArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement panorama : panoramaArray) {
                Panorama p = new Panorama();

                JsonObject panoramaObj = panorama.getAsJsonObject();

                p.setIdpanorama(panoramaObj.get("idpanorama").getAsString());
                p.setEnlace(panoramaObj.get("enlace").getAsString());
                if (panoramaObj.has("panorama")) {
                    p.setPanorama(panoramaObj.get("panorama").getAsInt());
                }

                lu.add(p);
            }

            e.setPanoramas(lu);

            List<Profesor> lp = new ArrayList<Profesor>();
            if (jsonObject.has("profesores")) {
                JsonArray profesorArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement profesor : profesorArray) {
                    Profesor p = new Profesor();

                    JsonObject profesorObj = profesor.getAsJsonObject();
                    p.setIdprofesor(profesorObj.get("idprofesor").getAsString());
                    p.setUsuario(profesorObj.get("usuario").getAsString());
                    p.setVisibilidad(profesorObj.get("visibilidad").getAsBoolean());
                    lp.add(p);
                }
            }
            e.setProfesores(lp);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    Type listType = new TypeToken<List<Espacio>>() {
    }.getType();

    Gson customGson = gsonBuilder.create();
    List<Espacio> jsonToEspacios = customGson.fromJson(espaciosJSON, listType);

    // System.out.println("Success Espacio: "+ jsonToEspacios.size());

    return jsonToEspacios;

}

From source file:bitrefill.retrofit.Config.java

public Config(JsonObject json) {
    if (json == null)
        return;/*from   w w w  .  j ava2  s  . c o  m*/
    if (json.has("key"))
        setKey(json.get("key").getAsString());
    if (json.has("secret"))
        setSecret(json.get("secret").getAsString());
    if (json.has("url"))
        setURL(json.get("url").getAsString());
    if (json.has("logger"))
        setLogger(json.get("logger").getAsString());
    if (json.has("loggerLevel"))
        setLoggerLevel(json.get("loggerLevel").getAsString());
}

From source file:blockplus.transport.VirtualClient.java

License:Open Source License

@Override
public void onMessage(final String message) {
    final JsonParser jsonParser = new JsonParser();
    final JsonObject jsonObject = jsonParser.parse(message).getAsJsonObject();
    final String type = jsonObject.get("type").getAsString();
    if (type.equals("game")) {
        final JsonObject data = jsonObject.get("data").getAsJsonObject();
        final int k = data.get("players").getAsInt();
        this.color = Colors.values()[k - 1].toString();
    }//from w w w .  j  a  va2  s  .c  o  m
    if (type.equals("update")) {
        final JsonObject data = jsonObject.get("data").getAsJsonObject();

        //            System.out.println(data);

        final String color = data.get("color").getAsString();
        if (color.equals(this.color)) {
            if (data.get("isTerminal").getAsBoolean()) {
                System.out.println("Game Over");
            } else {

                final Colors side = Colors.valueOf(this.color);

                final BoardEncoding boardEncoding = new BoardEncoding();
                final Board board = boardEncoding.decode(data.get("board").getAsJsonObject());

                //                    final OptionsEncoding optionsEncoding = new OptionsEncoding();
                //                    final Options options = optionsEncoding.decode(data.get("options").getAsJsonObject());

                final SidesEncoding sidesEncoding = new SidesEncoding();
                final Sides sides = sidesEncoding.decode(data.get("pieces").getAsJsonObject());

                final Context context = new Context(side, sides, board);
                final AI3 ai = new AI3();

                //                    final IPosition position = this.testAI(side, board, options);
                //                    final Set<IPosition> positions = this.moveSupplier(options, position);

                System.out.println();
                System.out.println(side);
                final Set<IPosition> positions = ai.get(context);

                final JsonArray jsonArray = new JsonArray();
                for (final IPosition iPosition : positions)
                    jsonArray.add(new JsonPrimitive(20 * iPosition.row() + iPosition.column() % 20)); // TODO !!!

                final MoveSubmit moveSubmit = new MoveSubmit(jsonArray);

                try {
                    this.send(moveSubmit);
                } catch (final Exception e) {
                }
            }
        }
    }
}

From source file:blusunrize.immersiveengineering.client.models.ModelData.java

public static ModelData fromJson(JsonObject customData, Collection<String> knownKeys, String modelKey,
        ImmutableMap<String, String> texReplacements) {
    String baseLocStr = customData.get(modelKey).getAsString();
    ResourceLocation baseLoc = new ResourceLocation(baseLocStr);
    JsonObject customBase = new JsonObject();
    if (customData.has("custom"))
        customBase = customData.get("custom").getAsJsonObject();
    for (Entry<String, JsonElement> e : customData.entrySet())
        if (!knownKeys.contains(e.getKey()) && !customBase.has(e.getKey()))
            customBase.add(e.getKey(), e.getValue());
    if (customData.has("textures")) {
        JsonObject obj = customData.get("textures").getAsJsonObject();
        ImmutableMap.Builder<String, String> b = ImmutableMap.builder();
        b.putAll(texReplacements);/*  w  ww .  ja va 2 s.c o m*/
        b.putAll(asMap(obj, true));
        texReplacements = b.build();
    }
    return new ModelData(baseLoc, customBase, texReplacements);
}

From source file:blusunrize.immersiveengineering.common.crafting.RecipeFactoryIEItemRepair.java

@Override
public IRecipe parse(JsonContext context, JsonObject json) {
    Ingredient ingred = CraftingHelper.getIngredient(json.get("tool"), context);
    return new RecipeIEItemRepair(ingred);
}

From source file:blusunrize.immersiveengineering.common.util.advancements.MultiblockTrigger.java

@Override
public MultiblockTrigger.Instance deserializeInstance(JsonObject json, JsonDeserializationContext context) {
    return new MultiblockTrigger.Instance(JsonUtils.getString(json, "multiblock"),
            ItemPredicate.deserialize(json.get("item")));
}

From source file:bmw.assigment.BMWAssigment.java

/**
 * Recursive method to populate the data extracted from the Json file
 * //w w w . j  a  v a 2s  .  co m
 * @param employee
 * @return 
 */
public static AbstractEmployee populateSubordinate(JsonObject employee) {

    AbstractEmployee emp = null;

    if (employee.has("_subordinates")) {
        emp = new Manager(employee.get("_name").getAsString(), employee.get("_salary").getAsLong());
        JsonArray array = employee.getAsJsonArray("_subordinates");
        for (int i = 0; i < array.size(); i++) {
            emp.addEmployee(populateSubordinate(array.get(i).getAsJsonObject()));
        }
    } else {
        emp = new Employee(employee.get("_name").getAsString(), employee.get("_salary").getAsLong());
    }

    return emp;
}

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");
    }//www  . jav  a  2 s.  co 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;
}