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:au.edu.unsw.soacourse.client.ApplicationLogic.java

static public void getApps(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setCharacterEncoding("utf8");
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    try {/*from   w w w  .  ja  v a  2 s.c  o  m*/
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = request.getReader();
        String temp = "";
        while ((temp = reader.readLine()) != null) {
            sb.append(temp);
        }
        // System.out.println(sb.toString());
        // convert to object
        Gson gson = new Gson();
        JsonElement je = gson.fromJson(sb.toString(), JsonElement.class);
        JsonObject jo = je.getAsJsonObject();

        String profileID = "";
        if (jo.has("profileID"))
            profileID = jo.get("profileID").getAsString();

        // System.out.println(profileID);
        String REST_URI = "http://localhost:8080/RESTfulFoundITService/apps";
        REST_URI += "/profileID/" + profileID;

        WebClient client = WebClient.create(REST_URI);
        String s = client.get(String.class);
        // System.out.println(s);
        // write the json
        out.write(s);
        out.close();
    } catch (Exception e) {
        out.write("failed");
        e.printStackTrace();
        out.close();
    }

}

From source file:au.edu.unsw.soacourse.client.RegisterLogic.java

static public void getpro(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf8");
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    try {//from w  w w  .java2 s . c om
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = request.getReader();
        String temp = "";
        while ((temp = reader.readLine()) != null) {
            sb.append(temp);
        }
        // System.out.println(sb.toString());
        // convert to object
        Gson gson = new Gson();
        JsonElement je = gson.fromJson(sb.toString(), JsonElement.class);
        JsonObject jo = je.getAsJsonObject();

        String profileID = "";
        if (jo.has("profileID"))
            profileID = jo.get("profileID").getAsString();

        String REST_URI = "http://localhost:8080/RESTfulFoundITService/userProfiles";
        REST_URI += "/profile/" + profileID;

        WebClient client = WebClient.create(REST_URI);
        String s = client.get(String.class);
        // System.out.println(s);

        // write the json
        out.write(s);
        out.close();
    } catch (Exception e) {
        out.write("failed");
        e.printStackTrace();
        out.close();
    }

}

From source file:augsburg.se.alltagsguide.common.EventPage.java

License:Open Source License

@NonNull
public static EventPage fromJson(@NonNull final JsonObject jsonPage) {
    Page page = Page.fromJson(jsonPage);
    //TODO jsonPage.get("page") !?
    Event event = Event.fromJson(jsonPage.get("event").getAsJsonObject(), page.getId());
    JsonElement locationElement = jsonPage.get("location");
    EventLocation location = null;//from  w w  w .  j  av a 2  s.  com
    if (locationElement != null && !locationElement.isJsonNull()) {
        location = EventLocation.fromJson(locationElement.getAsJsonObject());
    }
    List<EventTag> tags = EventTag.fromJson(jsonPage.get("tags").getAsJsonArray());
    List<EventCategory> categories = EventCategory.fromJson(jsonPage.get("categories").getAsJsonArray());
    return new EventPage(page, event, location, tags, categories);
}

From source file:automatizacionrp.obtenerParametros.java

public static Parametros obtenerParametros() {
    log.info("Inicia proceso de obtencin de parmetros");
    try {/*from   www. ja  v  a2 s.  c  o  m*/
        pdi = Servicio.queryapp("SELECT  conf.json_config , pe.id_plan_ejecucion , "
                + "jo.job FROM public.config as conf, public.plan_ejecuciones as pe , "
                + "public.pasos_plan_ejecucion as ppe , public.jobs as jo WHERE conf.activo=true "
                + "and elemento='pdi' and pe.id_job=jo.id_job and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true and pe.timestamp_planificacion in "
                + "(SELECT min(pe.timestamp_planificacion) FROM public.config as conf, "
                + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe "
                + "WHERE conf.activo=true and elemento='pdi'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true) and pe.timestamp_planificacion::timestamp <= now()::timestamp LIMIT 1;");

    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error("Excepcin obteniendo parmetros pdi 1 :");
        log.error(e);
        pdi = "";
    }
    if (pdi.length() <= 2) {
        log.info("No existe planificacion pendiente");
        return param;
    }
    aux = "";
    pdi = pdi.substring(1, pdi.length() - 1);
    JsonParser parser = new JsonParser();
    JsonElement elementObject;
    elementObject = parser.parse(pdi);
    tipo = elementObject.getAsJsonObject().get("job").getAsString();
    id = elementObject.getAsJsonObject().get("id_plan_ejecucion").getAsString();

    try {
        cluster = Servicio.queryapp("SELECT  conf.json_config , pe.id_plan_ejecucion , "
                + "jo.job FROM public.config as conf, public.plan_ejecuciones as pe , "
                + "public.pasos_plan_ejecucion as ppe , public.jobs as jo WHERE conf.activo=true "
                + "and elemento='cluster' and pe.id_job=jo.id_job and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true and pe.timestamp_planificacion in "
                + "(SELECT min(pe.timestamp_planificacion) FROM public.config as conf, "
                + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe "
                + "WHERE conf.activo=true and elemento='cluster'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true) and pe.timestamp_planificacion::timestamp <= now()::timestamp limit 1;");

        bd_pys = Servicio.queryapp("SELECT  conf.json_config , pe.id_plan_ejecucion , jo.job "
                + "FROM public.config as conf, public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe, "
                + "public.jobs as jo WHERE conf.activo=true and elemento='bd_pys' and pe.id_job=jo.id_job "
                + "and pe.id_plan_ejecucion=ppe.id_plan_ejecucion and ppe.status_plan='en espera' and ppe.activo=true "
                + "and pe.timestamp_planificacion in (SELECT min(pe.timestamp_planificacion) FROM public.config as conf,"
                + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe WHERE conf.activo=true "
                + "and elemento='bd_pys'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion and ppe.status_plan='en espera' and ppe.activo=true) "
                + "and pe.timestamp_planificacion::timestamp <= now()::timestamp limit 1;");

        tienda = Servicio.queryapp(
                "SELECT t.tienda,t.host_bd_oracle,t.usuario_bd_oracle,t.pass_usuario_bd_oracle,t.bd_oracle\n"
                        + "  FROM public.plan_ejecuciones as pe,public.tiendas as t\n"
                        + "  where pe.id_plan_ejecucion=" + id + " and pe.id_tienda=t.id_tienda;");

    } catch (Exception e) {
        log.error("Excepcin obteniendo parmetros cluster , bd_pys y tienda :");
        log.error(e);
        tienda = "";
        cluster = "";
        bd_pys = "";
    }
    bandera = true;

    if (pdi.length() > 2) {
        if (existeCampo.existeCampo(pdi, "valor")) {
            aux = elementObject.getAsJsonObject().get("valor").getAsString();
            param.setTransformaciones(aux);
        }
        if (existeCampo.existeCampo(pdi, "timestamp_inicio_ejec")) {
            aux = elementObject.getAsJsonObject().get("timestamp_inicio_ejec").getAsString();
            param.setTimestampIni(aux);
        }
        if (existeCampo.existeCampo(pdi, "timestamp_fin_ejec")) {
            aux = elementObject.getAsJsonObject().get("timestamp_fin_ejec").getAsString();
            param.setTimestampFin(aux);
        }
        if (existeCampo.existeCampo(pdi, "id_plan_ejecucion")) {
            aux = elementObject.getAsJsonObject().get("id_plan_ejecucion").getAsString();
            param.setIdplanEjec(aux);
        }
        pdi = elementObject.getAsJsonObject().get("json_config").getAsString();
        elementObject = parser.parse(pdi);
        if (existeCampo.existeCampo(pdi, "directorio_pdi")) {
            aux = elementObject.getAsJsonObject().get("directorio_pdi").getAsString();
            param.setDirPDI(aux);
        }
        if (existeCampo.existeCampo(pdi, "repositorio")) {
            aux = elementObject.getAsJsonObject().get("repositorio").getAsString();
            param.setRepositorio(aux);
        }
        if (existeCampo.existeCampo(pdi, "usuario_repositorio")) {
            aux = elementObject.getAsJsonObject().get("usuario_repositorio").getAsString();
            param.setUsuarioRepositorio(aux);
        }
        if (existeCampo.existeCampo(pdi, "password")) {
            aux = elementObject.getAsJsonObject().get("password").getAsString();
            param.setPassusuarioRepo(aux);
        }
        if (existeCampo.existeCampo(pdi, "directorio_logs")) {
            aux = elementObject.getAsJsonObject().get("directorio_logs").getAsString();
            param.setDirLogs(aux);
        }
        if (existeCampo.existeCampo(pdi, "nivel_logs")) {
            aux = elementObject.getAsJsonObject().get("nivel_logs").getAsString();
            param.setNivelLogs(aux);
        }
        param.setNombreJob(tipo);

        if (bandera) {
            if (existeCampo.existeCampo(pdi, "directorio_job_ci")) {
                aux = elementObject.getAsJsonObject().get("directorio_job_ci").getAsString();
                param.setDirEjecucion(aux);
            }
        } else {
            if (existeCampo.existeCampo(pdi, "directorio_job_m")) {
                aux = elementObject.getAsJsonObject().get("directorio_job_m").getAsString();
                param.setDirEjecucion(aux);
            }
        }

        param.setJobModo("CARGA");
    } else {
        log.warn("No se obtuvieron los valores del PDI");
    }
    if (cluster.length() > 2) {
        aux = "";
        cluster = cluster.substring(1, cluster.length() - 1);
        elementObject = parser.parse(cluster);
        cluster = elementObject.getAsJsonObject().get("json_config").getAsString();
        if (existeCampo.existeCampo(cluster, "nodos")) {
            elementObject = parser.parse(cluster);
            cluster = elementObject.getAsJsonObject().get("nodos").toString();
            cluster = cluster.substring(1, cluster.length() - 1);
            StringTokenizer st = new StringTokenizer(cluster, "}");
            cluster = st.nextToken() + "}";
            elementObject = parser.parse(cluster);
            if (existeCampo.existeCampo(cluster, "host")) {
                aux = elementObject.getAsJsonObject().get("host").getAsString();
                param.setHostbdCassandra(aux);
            }
            if (existeCampo.existeCampo(cluster, "columnFamily")) {
                aux = elementObject.getAsJsonObject().get("columnFamily").getAsString();
                param.setColumnFamily(aux);
            }
            if (existeCampo.existeCampo(cluster, "keyspace")) {
                aux = elementObject.getAsJsonObject().get("keyspace").getAsString();
                param.setKeyspace(aux);
            }
        }
    } else {
        log.warn("No se obtuvieron los valores del cluster");
    }
    if (bd_pys.length() > 2) {
        aux = "";
        bd_pys = bd_pys.substring(1, bd_pys.length() - 1);
        elementObject = parser.parse(bd_pys);
        bd_pys = elementObject.getAsJsonObject().get("json_config").getAsString();
        elementObject = parser.parse(bd_pys);
        if (existeCampo.existeCampo(bd_pys, "host")) {
            aux = elementObject.getAsJsonObject().get("host").getAsString();
            param.setHostbdApp(aux);
        }
        if (existeCampo.existeCampo(bd_pys, "bd")) {
            aux = elementObject.getAsJsonObject().get("bd").getAsString();
            param.setBdApp(aux);
        }
        if (existeCampo.existeCampo(bd_pys, "usuario")) {
            aux = elementObject.getAsJsonObject().get("usuario").getAsString();
            param.setUsuariobdApp(aux);
        }
        if (existeCampo.existeCampo(bd_pys, "password")) {
            aux = elementObject.getAsJsonObject().get("password").getAsString();
            param.setPassusuariobdApp(aux);
        }
    } else {
        log.warn("No se obtuvieron los valores de bd_pys");
    }
    if (tienda.length() > 2) {
        aux = "";
        tienda = tienda.substring(1, tienda.length() - 1);
        elementObject = parser.parse(tienda);

        if (existeCampo.existeCampo(tienda, "usuario_bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("usuario_bd_oracle").getAsString();
            param.setUsuariobdOracle(aux);
        }
        if (existeCampo.existeCampo(tienda, "pass_usuario_bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("pass_usuario_bd_oracle").getAsString();
            param.setPassusuariobdOracle(aux);
        }
        if (existeCampo.existeCampo(tienda, "host_bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("host_bd_oracle").getAsString();
            param.setHostbdOracle(aux);
        }
        if (existeCampo.existeCampo(tienda, "bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("bd_oracle").getAsString();
            param.setBdOracle(aux);
        }
    } else {
        log.warn("No se obtuvieron los valores de las tiendas");
    }
    param.setTipo(tipo);
    return param;
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

License:MIT 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 MessageUtil} representing the parameterized JSON
 * message./*from  ww  w. j av a 2s.c  o  m*/
 */
public static MessageUtil deserialize(String json) {
    JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
    JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
    MessageUtil returnVal = new MessageUtil();
    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 MessageUtil
                    // 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 - MessageUtils
                        // 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:be.ugent.tiwi.sleroux.newsrec.recommendationstester.CustomDeserializer.java

@Override
public NewsItemCluster deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jo = json.getAsJsonObject();
    RecommendedNewsItem[] items = context.deserialize(jo.get("items"), RecommendedNewsItem[].class);

    RecommendedNewsItem rep = context.deserialize(jo.get("representative"), RecommendedNewsItem.class);
    NewsItemCluster cluster = new NewsItemCluster();
    cluster.setItems(Arrays.asList(items));
    cluster.setRepresentative(rep);/* w ww  . j av a2s  . c  o  m*/
    return cluster;
}

From source file:bean.EJBean.java

License:Open Source License

public Edificio getEdificio(String id) {

    client = ClientBuilder.newClient();// w ww  .  j  a  v a 2 s  .  co  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 www  .  ja va 2  s  .  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();/*from ww w .  j  a va  2 s  . 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:blusunrize.immersiveengineering.client.ClientProxy.java

public void addChangelogToManual() {
    FontRenderer fr = ManualHelper.getManual().fontRenderer;
    boolean isUnicode = fr.getUnicodeFlag();
    fr.setUnicodeFlag(true);/*from   ww w . j  a va 2  s  .c  om*/
    SortedMap<ComparableVersion, Pair<String, IManualPage[]>> allChanges = new TreeMap<>(
            Comparator.reverseOrder());
    ComparableVersion currIEVer = new ComparableVersion(ImmersiveEngineering.VERSION);
    //Included changelog
    try (InputStream in = Minecraft.getMinecraft().getResourceManager()
            .getResource(new ResourceLocation(ImmersiveEngineering.MODID, "changelog.json")).getInputStream()) {
        JsonElement ele = new JsonParser().parse(new InputStreamReader(in));
        JsonObject upToCurrent = ele.getAsJsonObject();
        for (Entry<String, JsonElement> entry : upToCurrent.entrySet()) {
            ComparableVersion version = new ComparableVersion(entry.getKey());
            Pair<String, IManualPage[]> manualEntry = addVersionToManual(currIEVer, version,
                    entry.getValue().getAsString(), false);
            if (manualEntry != null)
                allChanges.put(version, manualEntry);
        }
    } catch (IOException x) {
        x.printStackTrace();
    }
    //Changelog from update JSON
    CheckResult result = ForgeVersion.getResult(Loader.instance().activeModContainer());
    if (result.status != Status.PENDING && result.status != Status.FAILED)
        for (Entry<ComparableVersion, String> e : result.changes.entrySet())
            allChanges.put(e.getKey(), addVersionToManual(currIEVer, e.getKey(), e.getValue(), true));

    for (Pair<String, IManualPage[]> entry : allChanges.values())
        ManualHelper.addEntry(entry.getLeft(), ManualHelper.CAT_UPDATE, entry.getRight());
    fr.setUnicodeFlag(isUnicode);
}