List of usage examples for com.google.gson JsonObject has
public boolean has(String memberName)
From source file:bean.EJBean.java
License:Open Source License
public Edificio getEdificio(String id) { client = ClientBuilder.newClient();/*from ww w.j a v a 2s . c om*/ 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 ww . j av a 2s. co 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 w w w . j av 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. java2 s . c om*/ 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: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 . j a v a2s . c o m b.putAll(asMap(obj, true)); texReplacements = b.build(); } return new ModelData(baseLoc, customBase, texReplacements); }
From source file:bmw.assigment.BMWAssigment.java
/** * Recursive method to populate the data extracted from the Json file * //from w ww . j a v a2 s .c om * @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.saude.api.social.gcm.GcmServer.java
License:Open Source License
public GcmServer(String apiKey, String senderId, String serviceName) { jsonParser = new JsonParser(); gson = new GsonBuilder().create(); String username = senderId + "@" + Constants.GCM_HOST; smackCcsClient = new SmackCcsClient(apiKey, username, serviceName, Constants.GCM_HOST, Constants.GCM_CCS_PORT);/*from www .j a va 2s. c o m*/ System.out.println("smackCcsClient(" + apiKey + ", " + username + ", " + serviceName + ", " + Constants.GCM_HOST + ", " + Constants.GCM_CCS_PORT + ")\n"); // Add the GcmPacketExtension as an extension provider. ProviderManager.addExtensionProvider(Constants.GCM_ELEMENT_NAME, Constants.GCM_NAMESPACE, new ExtensionElementProvider<GcmPacketExtension>() { @Override public GcmPacketExtension parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException { String json = parser.nextText(); return new GcmPacketExtension(json); } }); stanzaFilter = new StanzaFilter() { @Override public boolean accept(Stanza stanza) { // Accept messages from GCM CCS. if (stanza.hasExtension(Constants.GCM_ELEMENT_NAME, Constants.GCM_NAMESPACE)) { return true; } // Reject messages that are not from GCM CCS. return false; } }; stanzaListener = new StanzaListener() { @Override public synchronized void processPacket(Stanza packet) throws SmackException.NotConnectedException { // Extract the GCM message from the packet. GcmPacketExtension packetExtension = (GcmPacketExtension) packet .getExtension(Constants.GCM_NAMESPACE); JsonObject jGcmMessage = jsonParser.parse(packetExtension.getJson()).getAsJsonObject(); String from = jGcmMessage.get("from").getAsString(); // If there is no message_type normal GCM message is assumed. if (!jGcmMessage.has("message_type")) { if (StringUtils.isNotEmpty(from)) { JsonObject jData = jGcmMessage.get("data").getAsJsonObject(); onMessage(from, jData); // Send Ack to CCS to confirm receipt of upstream message. String messageId = jGcmMessage.get("message_id").getAsString(); if (StringUtils.isNotEmpty(messageId)) { sendAck(from, messageId); } else { logger.log(Level.SEVERE, "Message ID is null or empty."); } } else { logger.log(Level.SEVERE, "From is null or empty."); } } else { // Handle message_type here. String messageType = jGcmMessage.get("message_type").getAsString(); if (messageType.equals("ack")) { // Handle ACK. Here the ack is logged, you may want to further process the ACK at this // point. String messageId = jGcmMessage.get("message_id").getAsString(); logger.info("ACK received for message " + messageId + " from " + from); } else if (messageType.equals("nack")) { // Handle NACK. Here the nack is logged, you may want to further process the NACK at // this point. String messageId = jGcmMessage.get("message_id").getAsString(); logger.info("NACK received for message " + messageId + " from " + from); } else if (messageType.equals("control")) { logger.info("Control message received."); String controlType = jGcmMessage.get("control_type").getAsString(); if (controlType.equals("CONNECTION_DRAINING")) { // Handle connection draining // SmackCcsClient only maintains one connection the CCS to reduce complexity. A real // world application should be capable of maintaining multiple connections to GCM, // allowing the application to continue to onMessage for incoming messages on the // draining connection and sending all new out going messages on a newly created // connection. logger.info("Current connection will be closed soon."); } else { // Currently the only control_type is CONNECTION_DRAINING, if new control messages // are added they should be handled here. logger.info("New control message has been received."); } } } } }; smackCcsClient.listen(stanzaListener, stanzaFilter); }
From source file:br.com.thiaguten.contrib.JsonContrib.java
License:Apache License
private static void deepJsonObjectSearchToJsonObjectFlattened(JsonObject jsonObject, JsonObject jsonObjectFlattened) { if (jsonObject == null || jsonObjectFlattened == null) { throw new IllegalArgumentException( "JsonObject and/or JsonObjectFlattened parameter(s) must not be null"); }//from w w w. j a v a 2 s. c om for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { deepJsonObjectSearchToJsonObjectFlattened((JsonObject) value, jsonObjectFlattened); } else if (value.isJsonArray()) { // Creates new flattened JsonArray instance. JsonArray jsonArray = new JsonArray(); // Iterates recursively in JsonArray (value), checking content and populating the flattened JsonArray instance. deepJsonArraySearchToJsonArrayFlattened((JsonArray) value, jsonArray); // Adds the flattened JsonArray instance in the flattened JsonObject instance. jsonObjectFlattened.add(key, jsonArray); } else { // FIXME - WORKAROUND // Attention: A map can not contain duplicate keys. So, the // duplicate key is concatenated with a counter, to avoid data // loss. I could not think of anything better yet. if (jsonObjectFlattened.has(key)) { jsonObjectFlattened.add(key + COUNTER.getAndIncrement(), value); } else { jsonObjectFlattened.add(key, value); } } } }
From source file:br.net.fabiozumbi12.redprotect.MojangUUIDs.java
License:Open Source License
public static String getName(String UUID) { try {/*from w w w . j a v a 2s . c o m*/ URL url = new URL("https://api.mojang.com/user/profiles/" + UUID.replaceAll("-", "") + "/names"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); if (line == null) { return null; } JsonArray array = (JsonArray) new JsonParser().parse(line); HashMap<Long, String> names = new HashMap<Long, String>(); String name = ""; for (Object profile : array) { JsonObject jsonProfile = (JsonObject) profile; if (jsonProfile.has("changedToAt")) { names.put(jsonProfile.get("changedToAt").getAsLong(), jsonProfile.get("name").getAsString()); continue; } name = jsonProfile.get("name").getAsString(); } if (!names.isEmpty()) { Long key = Collections.max(names.keySet()); return names.get(key); } else { return name; } } catch (Exception ex) { ex.printStackTrace(); } return null; }
From source file:br.unicamp.cst.bindings.soar.JSoarCodelet.java
License:Open Source License
public ArrayList<Object> getCommandsJSON(String package_with_beans_classes) { ArrayList<Object> commandList = new ArrayList<Object>(); JsonObject templist = getJsoar().getOutputLinkJSON(); Set<Map.Entry<String, JsonElement>> set = templist.entrySet(); Iterator<Entry<String, JsonElement>> it = set.iterator(); while (it.hasNext()) { Entry<String, JsonElement> entry = it.next(); String key = entry.getKey(); JsonObject commandtype = entry.getValue().getAsJsonObject(); try {//w w w. j av a 2s. c o m Class type = Class.forName(package_with_beans_classes + "." + key); Object command = type.newInstance(); type.cast(command); for (Field field : type.getFields()) { if (commandtype.has(field.getName())) { if (commandtype.get(field.getName()).getAsJsonPrimitive().isNumber()) { field.set(command, commandtype.get(field.getName()).getAsFloat()); } else if (commandtype.get(field.getName()).getAsJsonPrimitive().isBoolean()) { field.set(command, commandtype.get(field.getName()).getAsBoolean()); } else { field.set(command, commandtype.get(field.getName()).getAsString()); } } } commandList.add(command); } catch (Exception e) { e.printStackTrace(); } } return commandList; }