List of usage examples for com.google.gson JsonObject getAsString
public String getAsString()
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./* ww w.ja va2 s. c om*/ */ 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:ch.usz.c3pro.c3_pro_android_framework.dataqueue.jobs.CreateResourceJobEncrypted.java
License:Open Source License
@Override public void onRun() throws Throwable { try {/*from www . jav a 2 s . c o m*/ JsonObject jasonToSend = EncryptedDataQueue.getInstance().encryptResource(uploadResource); IGenericClient client = Pyro.getFhirContext().newRestfulGenericClient(serverURL); MethodOutcome outcome = client.create().resource(jasonToSend.getAsString()).prettyPrint().encodedJson() .execute(); //TODO decide what to do when upload does not return anything Log.d(Logging.asyncLogTag, "created resource with id " + outcome.getId().getValue()); } catch (GeneralSecurityException e) { e.printStackTrace(); callback.onFail(uploadResource, C3PROErrorCode.ENCRYPTION_EXCEPTION.addThrowable(e)); } }
From source file:co.vaughnvernon.actormodel.util.serializer.PropertiesSerializer.java
License:Apache License
public String serialize(Properties aProperties) { JsonObject object = new JsonObject(); for (Object keyObj : aProperties.keySet()) { String key = keyObj.toString(); String value = aProperties.getProperty(key); object.addProperty(key, value);// www . ja v a 2 s . c om } return object.getAsString(); }
From source file:com.github.easyjsonapi.adapters.EasyJsonApiDeserializer.java
License:Apache License
/** * Deserializer when occur an error//ww w . j a v a 2 s . co m * * @param jsonElem * the json element * @param jsonContext * the json context * @return the json api object with values created */ private JsonApi deserializerError(JsonElement jsonElem, JsonDeserializationContext jsonContext) { JsonApi request = new JsonApi(); JsonArray jsonArrayErrors = jsonElem.getAsJsonObject().get("errors").getAsJsonArray(); // Iterate the errors list for (int index = 0; index < jsonArrayErrors.size(); index++) { JsonObject jsonError = jsonArrayErrors.get(index).getAsJsonObject(); String jsonApiErrorDetail = JsonTools.getStringInsideJson("detail", jsonError); String jsonApiErrorCode = JsonTools.getStringInsideJson("code", jsonError); String jsonApiErrorTitle = JsonTools.getStringInsideJson("title", jsonError); String jsonApiErrorId = JsonTools.getStringInsideJson("id", jsonError); Source jsonApiErrorSource = null; HttpStatus jsonApiErrorStatus = null; // Get the source json if (Assert.notNull(jsonError.get("source"))) { JsonObject jsonErrorSource = jsonError.get("source").getAsJsonObject(); jsonApiErrorSource = jsonContext.deserialize(jsonErrorSource, Source.class); } // Get the http status json if (Assert.notNull(jsonError.get("status"))) { JsonObject jsonErrorStatus = jsonError.get("status").getAsJsonObject(); jsonApiErrorStatus = HttpStatus.getStatus(Integer.valueOf(jsonErrorStatus.getAsString())); } Error jsonApiError = new Error(jsonApiErrorId, jsonApiErrorTitle, jsonApiErrorStatus, jsonApiErrorCode, jsonApiErrorDetail, Nullable.OBJECT, jsonApiErrorSource); request.addError(jsonApiError); } return request; }
From source file:com.graphaware.module.es.search.Searcher.java
License:Open Source License
private <T extends PropertyContainer> List<SearchMatch<T>> buildSearchMatches(SearchResult searchResult) { List<SearchMatch<T>> matches = new ArrayList<>(); Set<Map.Entry<String, JsonElement>> entrySet = searchResult.getJsonObject().entrySet(); entrySet.stream().filter((item) -> (item.getKey().equalsIgnoreCase("hits"))) .map((item) -> (JsonObject) item.getValue()).filter((hits) -> (hits != null)) .map((hits) -> hits.getAsJsonArray("hits")).filter((hitsArray) -> (hitsArray != null)) .forEach((hitsArray) -> { for (JsonElement element : hitsArray) { JsonObject obj = (JsonObject) element; Double score = obj.get("_score") != null && !obj.get("_score").toString().equals("null") ? Double.valueOf(obj.get("_score").toString()) : null;/*w w w .j a v a 2s .c o m*/ String keyValue = obj.get("_id") != null ? obj.get("_id").getAsString() : null; if (keyValue == null) { LOG.warn("No key found in search result: " + obj.getAsString()); } else { matches.add(new SearchMatch<>(keyValue, score)); } } }); return matches; }
From source file:com.ibm.common.geojson.as2.GeoAdapter.java
License:Apache License
@Override public GeoObject deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { GeoObject.Builder geo = null;//w ww . ja v a2 s . c o m checkArgument(element.isJsonObject()); JsonObject obj = element.getAsJsonObject(); checkArgument(obj.has("type")); GeoObject.Type et = Enums.getIfPresent(GeoObject.Type.class, obj.get("type").getAsString().toUpperCase()) .orNull(); checkArgument(et != null); switch (et) { case FEATURE: geo = GeoMakers.feature(); break; case FEATURECOLLECTION: geo = GeoMakers.featureCollection(); type = Feature.class; break; case GEOMETRYCOLLECTION: geo = GeoMakers.geometryCollection(); type = Geometry.class; break; case LINESTRING: geo = GeoMakers.linestring(); type = Position.class; break; case MULTILINESTRING: geo = GeoMakers.multiLineString(); type = LineString.class; break; case MULTIPOINT: geo = GeoMakers.multipoint(); type = Position.class; break; case MULTIPOLYGON: geo = GeoMakers.multiPolygon(); type = Polygon.class; break; case POINT: geo = GeoMakers.point(); type = null; break; case POLYGON: geo = GeoMakers.polygon(); type = LineString.class; break; } for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { JsonElement el = entry.getValue(); String name = entry.getKey(); if ("crs".equals(name)) { CRS.Builder cb = new CRS.Builder(); JsonObject o = el.getAsJsonObject(); if (o.has("type")) cb.type(o.get("type").getAsString()); if (o.has("properties")) { JsonObject p = o.get("properties").getAsJsonObject(); for (Map.Entry<String, JsonElement> e : p.entrySet()) { cb.set(e.getKey(), context.deserialize(e.getValue(), Object.class)); } } geo.crs(cb.get()); } else if ("properties".equals(name)) { geo.set("properties", context.deserialize(el, Map.class)); } else if ("bbox".equals(name)) { BoundingBox.Builder bb = new BoundingBox.Builder(); float[] points = context.deserialize(el, float[].class); bb.add(points); geo.boundingBox(bb.get()); } else if ("features".equals(name)) { Feature[] features = context.deserialize(el, Feature[].class); FeatureCollection.Builder fcb = (FeatureCollection.Builder) geo; for (Feature f : features) fcb.add(f); } else if ("coordinates".equals(name)) { switch (et) { case LINESTRING: { LineString.Builder lsb = (LineString.Builder) geo; float[][] positions = context.deserialize(el, float[][].class); boolean ring = ring(positions); if (ring) lsb.linearRing(); for (int n = 0; n < positions.length; n++) { if (!ring || (ring && n < positions.length - 1)) lsb.add(toPosition(positions[n])); } break; } case MULTIPOINT: { MultiPoint.Builder lsb = (MultiPoint.Builder) geo; float[][] positions = context.deserialize(el, float[][].class); for (float[] pos : positions) lsb.add(toPosition(pos)); break; } case MULTILINESTRING: { MultiLineString.Builder mlb = (MultiLineString.Builder) geo; float[][][] positions = context.deserialize(el, float[][][].class); for (float[][] lines : positions) { LineString.Builder lsb = GeoMakers.linestring(); boolean ring = ring(lines); if (ring) lsb.linearRing(); for (int n = 0; n < lines.length; n++) { if (!ring || (ring && n < lines.length - 1)) lsb.add(toPosition(lines[n])); } for (float[] pos : lines) lsb.add(toPosition(pos)); mlb.add(lsb); } break; } case POLYGON: { Polygon.Builder mlb = (Polygon.Builder) geo; float[][][] positions = context.deserialize(el, float[][][].class); for (float[][] lines : positions) { LineString.Builder lsb = GeoMakers.linestring(); for (float[] pos : lines) lsb.add(toPosition(pos)); mlb.add(lsb); } break; } case MULTIPOLYGON: { MultiPolygon.Builder mpb = (MultiPolygon.Builder) geo; float[][][][] positions = context.deserialize(el, float[][][][].class); for (float[][][] polygons : positions) { Polygon.Builder pb = GeoMakers.polygon(); for (float[][] lines : polygons) { LineString.Builder lsb = GeoMakers.linestring(); for (float[] pos : lines) lsb.add(toPosition(pos)); pb.add(lsb); } mpb.add(pb); } break; } case POINT: Point.Builder pb = (Point.Builder) geo; float[] position = context.deserialize(el, float[].class); pb.position(toPosition(position)); break; default: break; } } else if ("geometries".equals(name)) { Geometry[] geos = context.deserialize(el, Geometry[].class); GeometryCollection.Builder fcb = (GeometryCollection.Builder) geo; for (Geometry<?, ?> g : geos) fcb.add(g); } else { if (el.isJsonArray()) { geo.set(name, context.deserialize(el, Object.class)); } else if (el.isJsonObject()) { geo.set(name, context.deserialize(el, GeoObject.class)); } else if (el.isJsonPrimitive()) { JsonPrimitive p = el.getAsJsonPrimitive(); if (p.isBoolean()) geo.set(name, p.getAsBoolean()); else if (p.isNumber()) geo.set(name, p.getAsNumber()); else if (p.isString()) geo.set(name, p.getAsString()); } } } return geo.get(); }
From source file:com.shareif.bungeeCordDynamicServerPool.RestServer.java
@GET @Path("/server/{name}") @Produces(MediaType.APPLICATION_JSON)/*from w w w.j a v a 2 s. c o m*/ public String get(@HeaderParam("signature") String _signature, @HeaderParam("time") int _time, @PathParam("name") String _name) throws IOException, NoSuchAlgorithmException { if (!WebServer.getInstance().validateAuthToken(_signature, _time, "/cluster/name/" + _name, "GET")) { throw new WebApplicationException(401); } Map<String, ServerInfo> cluster = ClusterManager.getInstance().getServers(); if (!cluster.containsKey(_name)) { throw new WebApplicationException(404); } ServerInfo server = cluster.get(_name); JsonObject s = new JsonObject(); s.addProperty("name", server.getName()); s.addProperty("motd", server.getMotd()); s.addProperty("address", server.getAddress().getAddress().toString()); s.addProperty("port", server.getAddress().getPort()); JsonObject players = new JsonObject(); for (ProxiedPlayer player : server.getPlayers()) { players.addProperty(player.getUniqueId().toString(), player.getDisplayName()); } s.add("players", players); return s.getAsString(); }
From source file:com.skyisland.questmanager.fanciful.FancyMessage.java
License:Open Source 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 FancyMessage} representing the parameterized JSON message. */// w w w .ja v a 2 s . co m public static FancyMessage deserialize(String json) { JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component FancyMessage returnVal = new FancyMessage(); 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 FancyMessage // 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 - FancyMessages // 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:io.github.prison.chat.FancyMessage.java
License:Open Source 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 FancyMessage} representing the parameterized JSON message. *///from ww w .j a v a 2s . co m public static FancyMessage deserialize(String json) { JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component FancyMessage returnVal = new FancyMessage(); 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<String, Object>(); // 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 FancyMessage // 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 - FancyMessages // 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:opendap.auth.UserProfile.java
License:Open Source License
/** public String getAffiliation() {/*w w w . ja v a 2 s . c o m*/ return (String) _jsonInit.get("affiliation"); } public void setAffiliation(String s) { _jsonInit.put("affiliation", s); } public String getFirstName() { return (String) _jsonInit.get("first_name"); } public void setFirstName(String s) { _jsonInit.put("first_name", s); } public String getStudyArea() { return (String) _jsonInit.get("study_area"); } public void setStudyArea(String s) { _jsonInit.put("study_area", s); } public void setUID(String s) { _jsonInit.put("uid", s); } public String getUserType() { return (String) _jsonInit.get("user_type"); } public void setUserType(String s) { _jsonInit.put("user_type", s); } public String getLastName() { return (String) _jsonInit.get("last_name"); } public void setLastName(String s) { _jsonInit.put("last_name", s); } public String getEmailAddress() { return (String) _jsonInit.get("email_address"); } public void setEmailAddress(String s) { _jsonInit.put("email_address", s); } public String getCountry() { return (String) _jsonInit.get("country"); } public void setCountry(String s) { _jsonInit.put("country", s); } **/ public String toString() { StringBuilder sb = new StringBuilder(); Gson gson = new Gson(); String jsonString = gson.toJson(_jsonInit); JsonObject externalRepresentation = gson.fromJson(jsonString, JsonObject.class); ; externalRepresentation.add("groups", gson.fromJson(gson.toJson(_groups), JsonObject.class)); externalRepresentation.add("roles", gson.fromJson(gson.toJson(_roles), JsonObject.class)); sb.append("UserProfile:").append(externalRepresentation.getAsString()); return sb.toString(); }