List of usage examples for com.google.gson JsonObject entrySet
public Set<Map.Entry<String, JsonElement>> entrySet()
From source file:com.kurtraschke.septa.gtfsrealtime.services.TransitViewService.java
License:Apache License
public Collection<Bus> getBuses() throws URISyntaxException, ClientProtocolException, IOException { URIBuilder b = new URIBuilder("http://www3.septa.org/hackathon/TransitViewAll/"); CloseableHttpClient client = HttpClients.custom().setConnectionManager(_connectionManager).build(); HttpGet httpget = new HttpGet(b.build()); try (CloseableHttpResponse response = client.execute(httpget); InputStream responseInputStream = response.getEntity().getContent(); Reader responseEntityReader = new InputStreamReader(responseInputStream)) { JsonParser parser = new JsonParser(); JsonObject root = (JsonObject) parser.parse(responseEntityReader); JsonArray routes = (JsonArray) Iterables.getOnlyElement(root.entrySet()).getValue(); List<Bus> allBuses = new ArrayList<>(); for (JsonElement routeElement : routes) { JsonArray buses = ((JsonArray) (Iterables.getOnlyElement(((JsonObject) routeElement).entrySet()) .getValue()));// ww w . j a va 2 s . c om for (JsonElement busElement : buses) { JsonObject busObject = (JsonObject) busElement; try { allBuses.add(new Bus(busObject.get("lat").getAsDouble(), busObject.get("lng").getAsDouble(), busObject.get("label").getAsString(), busObject.get("VehicleID").getAsString(), busObject.get("BlockID").getAsString(), busObject.get("Direction").getAsString(), (!(busObject.get("destination") instanceof JsonNull)) ? busObject.get("destination").getAsString() : null, busObject.get("Offset").getAsInt())); } catch (Exception e) { _log.warn("Exception processing bus JSON", e); _log.warn(busObject.toString()); } } } return allBuses; } }
From source file:com.learn.mobile.library.dmobi.helper.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }// w ww. j a v a2 s . c o m final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); // JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); // Do not remove typeFieldName JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); }
From source file:com.lithium.luces.Luces.java
License:Apache License
@Override public Luces mapping(String typename, JsonObject mapping) { if (log.isDebugEnabled()) { log.debug("Adding mapping for type " + typename); }/*from w w w. jav a 2 s . c om*/ if (log.isTraceEnabled()) { log.trace("Sending mapping: " + new GsonBuilder().setPrettyPrinting().create().toJson(mapping)); } if (null == typename || null == mapping) { if (errIfMappingNull) { throw new IllegalStateException( String.format("%1$s cannot be set to null", typename == null ? "Type" : "Mapping")); } log.warn("Setting mapping and type to null, no primitive type conversion will be done"); typeName = null; typeMap = null; } else { typeName = typename; typeMap = new HashMap<>(); JsonObject workingJson = mapping.getAsJsonObject(typename); if (null == workingJson) { throw new NoSuchElementException(typename + " type not present or misnamed in mapping"); } // TODO account for nesting workingJson = workingJson.getAsJsonObject("properties"); for (Entry<String, JsonElement> entry : workingJson.entrySet()) { JsonElement typeElt = entry.getValue().getAsJsonObject().get("type"); if (null == typeElt) { throw new NoSuchElementException( "Invalid mapping: No type defined for " + entry.getKey() + " field."); } ParseType parseType; try { parseType = ParseType.valueOf(typeElt.getAsString().toUpperCase()); } catch (UnsupportedOperationException ex) { throw new UnsupportedOperationException( "Invalid Mapping: Type defined is not a string: " + typeElt.toString()); } catch (IllegalArgumentException illegal) { throw new UnsupportedOperationException( "The " + typeElt.getAsString() + " type is not supported for conversion"); } typeMap.put(entry.getKey(), parseType); } } return this; }
From source file:com.ls.util.internal.ObjectComparator.java
License:Open Source License
private static Object getDifferencesMapForObjects(JsonObject origin, JsonObject patched) { final Map<String, Object> result = new HashMap<String, Object>(); //Create origin entry set Set<String> originKeySet = new HashSet<String>();//Later here will be only keys, removed in patched version. for (Entry<String, JsonElement> entry : origin.entrySet()) { originKeySet.add(entry.getKey()); }/* w w w. jav a 2 s. c o m*/ for (Entry<String, JsonElement> entry : patched.entrySet()) { originKeySet.remove(entry.getKey()); Object difference = getDifferencesObject(origin.get(entry.getKey()), entry.getValue()); if (difference != UNCHANGED) { result.put(entry.getKey(), difference); } } for (String key : originKeySet) { result.put(key, null); } if (result.isEmpty()) { return UNCHANGED; } else { return result; } }
From source file:com.ls.util.internal.ObjectComparator.java
License:Open Source License
private static Map<String, Object> getMapFromJsonElement(JsonObject object) { Map<String, Object> result = new HashMap<String, Object>(); for (Entry<String, JsonElement> entry : object.entrySet()) { result.put(entry.getKey(), convertElementToStringRepresentation(entry.getValue())); }// w w w .j a va 2s. c o m return result; }
From source file:com.ludo.efialtes.util.GsonPrettyPrinter.java
License:Open Source License
private List<String> objectToStringList(final JsonObject jsonObject) { final Map<String, List<String>> slm = new HashMap<String, List<String>>(); for (final Entry<String, JsonElement> e : jsonObject.entrySet()) { slm.put(e.getKey(), toStringList(e.getValue())); }/*from w w w.j a v a 2 s . c o m*/ final LinkedList<String> ret = new LinkedList<String>(); ret.add(""); ret.add("{"); int oPos = 0; for (final Entry<String, List<String>> e : orderEntrySet(slm.entrySet())) { oPos++; final int slLen = e.getValue().size(); int pos = 0; for (final String s : e.getValue()) { pos++; final boolean needComma = (pos == slLen && oPos < slm.size()); if (pos == 1) { ret.add(indent + "\"" + e.getKey() + "\" : " + s + (needComma ? ", " : "")); } else { ret.add(indent + s + (needComma ? ", " : "")); } } } ret.add("}"); return ret; }
From source file:com.lunix.cheata.utils.file.mod.ModEnabled.java
License:Open Source License
public static void loadMods() { Client.getFileManager();/*from w ww . ja va2 s. co m*/ if (!new File(FileManager.getDir(), fileName).exists()) { FileManager.createFile(fileName); return; } if (FileManager.readFile(fileName).isEmpty()) { return; } String fileContents = FileManager.readFile(fileName); try { JsonObject json = (JsonObject) new JsonParser().parse(fileContents); for (Entry<String, JsonElement> entry : json.entrySet()) { for (Mod mod : Client.getModManager().mods) { if (entry.getKey().equalsIgnoreCase(mod.getName())) { mod.setEnabled(entry.getValue().getAsBoolean()); Minecraft.logger.info("Set " + mod.getName() + " enabled to " + mod.isEnabled()); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.lunix.cheata.utils.file.mod.ModSettings.java
License:Open Source License
public static void loadMods() { Client.getFileManager();//w w w . j a v a2s. c om if (!new File(FileManager.getDir(), fileName).exists()) { FileManager.createFile(fileName); return; } if (FileManager.readFile(fileName).isEmpty()) { return; } String fileContents = FileManager.readFile(fileName); try { JsonObject json = (JsonObject) new JsonParser().parse(fileContents); for (Entry<String, JsonElement> entry : json.entrySet()) { ModValue value = Client.getValueManager().getValueByName(entry.getKey()); if (entry.getKey().equalsIgnoreCase(value.getValueName())) { if (value.isBoolean()) { Minecraft.logger.info("Set " + value.getValueName() + " to " + value.getValueBoolean()); value.setValueBoolean(entry.getValue().getAsBoolean()); } else { Minecraft.logger.info("Set " + value.getValueName() + " to " + value.getValueDouble()); value.setValueDouble(entry.getValue().getAsDouble()); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.make.json2java.Json2Java.java
License:Apache License
private void generateClasses(ClassDefCollection classes, JsonObject root, String pkg, String className) throws IOException { ClassDefinition classDef = classes.addClassDefinition(pkg, className); for (Map.Entry<String, JsonElement> element : root.entrySet()) { String name = element.getKey(); JsonElement value = element.getValue(); String type = Utils.lowerCaseUnderscoreToCamelCase(name, true); name = Utils.lowerCaseUnderscoreToCamelCase(name, false); if (value instanceof JsonPrimitive) { classDef.addField(new ClassField(name, value, type, false)); } else if (value instanceof JsonArray) { classDef.addImport("java.util.List"); classDef.addField(new ClassField(name, value, type, true)); JsonArray array = value.getAsJsonArray(); for (JsonElement arrayElement : array) { if (arrayElement instanceof JsonObject) { // Use all elements of the array generateClasses(classes, arrayElement.getAsJsonObject(), pkg, type); }// w w w.ja v a 2s . c om } } if (value instanceof JsonObject) { classDef.addField(new ClassField(name, value, type, false)); generateClasses(classes, value.getAsJsonObject(), pkg, type); } } }
From source file:com.mastertheboss.jmsbrowser.EJBBrowser.java
public List<QueueDTO> getListQueues() { String host = properties.getProperty("host"); int port = Integer.parseInt(properties.getProperty("port")); System.out.println("PORT---->" + port); final ModelNode req = new ModelNode(); req.get(ClientConstants.OP).set("read-children-resources"); req.get("child-type").set("jms-queue"); String mode = properties.getProperty("mode"); if (mode.equals("domain")) { req.get(ClientConstants.OP_ADDR).add("profile", properties.getProperty("profile")); }//from w w w. j av a2 s .co m req.get(ClientConstants.OP_ADDR).add("subsystem", "messaging"); req.get(ClientConstants.OP_ADDR).add("hornetq-server", "default"); ModelControllerClient client = null; List<QueueDTO> listQueues = new ArrayList(); try { client = ModelControllerClient.Factory.create(InetAddress.getByName(host), port); final ModelNode resp = client.execute(new OperationBuilder(req).build()); List<ModelNode> list = resp.get(ClientConstants.RESULT).asList(); for (ModelNode node : list) { String json = node.toJSONString(true); JsonObject res = new JsonParser().parse(json).getAsJsonObject(); Set<Map.Entry<String, JsonElement>> es = res.entrySet(); for (Map.Entry<String, JsonElement> entry : es) { QueueDTO queue = new QueueDTO(); queue.setName(entry.getKey()); JsonElement element = entry.getValue(); JsonObject obj = element.getAsJsonObject(); JsonElement binding = obj.get("entries"); queue.setEntry(binding.getAsString()); listQueues.add(queue); } } } catch (Exception exc) { exc.printStackTrace(); } return listQueues; }