List of usage examples for com.google.gson JsonElement getAsJsonPrimitive
public JsonPrimitive getAsJsonPrimitive()
From source file:com.continuuity.loom.macro.Expander.java
License:Apache License
/** * Given a JSON tree, find the element specified by the path (or the root if path is null). In that subtree, * recursively traverse all elements, and expand all String typed right hand side values. If a macro cannot be * expanded due to the cluster object missing certain data, that macro will be left unexpanded. * * @param json A JSON tree/* w w w. j a v a2 s .c om*/ * @param path the path to expand under * @param cluster the cluster to use for expanding macros. * @param nodes the cluster nodes to use for expanding macros. * @param node the cluster node to use for expanding macros. * @return a new JSON tree if any expansion took place, and the original JSON tree otherwise. * @throws SyntaxException if a macro expression is ill-formed. * @throws IncompleteClusterException if the cluster does not have the meta data to expand all macros. */ public static JsonElement expand(JsonElement json, @Nullable java.util.List<String> path, Cluster cluster, Set<Node> nodes, Node node) throws SyntaxException, IncompleteClusterException { // if path is given, if (path != null && !path.isEmpty()) { String first = path.get(0); if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonElement json1 = object.get(first); if (json1 != null) { JsonElement expanded = expand(json1, path.subList(1, path.size()), cluster, nodes, node); if (expanded != json1) { // only construct new json object if actual expansion happened JsonObject object1 = new JsonObject(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { object1.add(entry.getKey(), entry.getKey().equals(first) ? expanded : entry.getValue()); } return object1; } } } // path was given, but either no corresponding subtree was found or no expansion happened... return json; } if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { String value = primitive.getAsString(); String expanded = expand(value, cluster, nodes, node); if (!expanded.equals(value)) { // only return a new json element if actual expansion happened return new JsonPrimitive(expanded); } } } if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); JsonArray array1 = new JsonArray(); boolean expansionHappened = false; for (JsonElement element : array) { JsonElement expanded = expand(element, path, cluster, nodes, node); if (expanded != element) { expansionHappened = true; } array1.add(expanded); } // only return a new json array if actual expansion happened if (expansionHappened) { return array1; } } if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonObject object1 = new JsonObject(); boolean expansionHappened = false; for (Map.Entry<String, JsonElement> entry : object.entrySet()) { JsonElement expanded = expand(entry.getValue(), path, cluster, nodes, node); if (expanded != entry.getValue()) { expansionHappened = true; } object1.add(entry.getKey(), expand(entry.getValue(), path, cluster, nodes, node)); } if (expansionHappened) { return object1; } } return json; }
From source file:com.couchbase.cbadmin.client.RebalanceInfo.java
License:Open Source License
public RebalanceInfo(JsonObject obj) throws RestApiException { JsonElement e = obj.get("status"); if (e == null || e.isJsonPrimitive() == false) { throw new RestApiException("Expected status string", obj); }/*from ww w . java 2s .com*/ String sStatus = e.getAsString(); if (sStatus.equals("none")) { completed = true; } else if (sStatus.equals("running")) { for (Entry<String, JsonElement> ent : obj.entrySet()) { if (ent.getKey().equals("status")) { continue; } JsonObject progressObj; if (ent.getValue().isJsonObject() == false) { throw new RestApiException("Expected object", ent.getValue()); } progressObj = ent.getValue().getAsJsonObject(); JsonElement progressNum = progressObj.get("progress"); if (progressNum.isJsonPrimitive() == false || progressNum.getAsJsonPrimitive().isNumber() == false) { throw new RestApiException("Expected 'progress' to be number", progressNum); } details.put(ent.getKey(), progressNum.getAsNumber().floatValue() * 100); } } }
From source file:com.couchbase.plugin.basement.api.Client.java
License:Open Source License
private void addJsonElement(String key, JsonElement value, HashMap<String, Object> map) { if (value.isJsonArray()) { JsonArray jsonArray = value.getAsJsonArray(); ArrayList listAsValue = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> listElementMap = new HashMap<String, Object>(); Iterator<JsonElement> jsonArrayIterator = jsonArray.iterator(); while (jsonArrayIterator.hasNext()) { JsonElement jsonElement = jsonArrayIterator.next(); listAsValue.add(parse(jsonElement.toString())); }//from w ww . ja v a 2s. co m map.put(key, listAsValue); } else if (value.isJsonPrimitive()) { // check the type using JsonPrimitive // TODO: check all types JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive(); if (jsonPrimitive.isNumber()) { map.put(key, jsonPrimitive.getAsInt()); } else { map.put(key, jsonPrimitive.getAsString()); } } else { map.put(key, parse(value.toString())); } }
From source file:com.dabay6.libraries.androidshared.json.DateDeserializer.java
License:Open Source License
/** * {@inheritDoc}//from ww w .j a va 2s . c o m */ @Override public Date deserialize(final JsonElement json, final Type type, final JsonDeserializationContext context) throws JsonParseException { final Pattern pattern = Pattern.compile("/(Date\\((.?)(\\+.)?\\))/"); final Matcher matcher = pattern.matcher(json.getAsJsonPrimitive().getAsString()); final String result = matcher.replaceAll("$2"); return new Date(Long.valueOf(result)); }
From source file:com.daon.identityx.samplefidoapp.RelyingPartyServerComms.java
License:Apache License
public RelyingPartyServerComms(Context context) { builder = new GsonBuilder(); // builder.registerTypeAdapter(Timestamp.class, new JsonDeserializer<Timestamp>() { // public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // return new Timestamp(json.getAsJsonPrimitive().getAsLong()); // } // }); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); try { String dateAsString = json.getAsJsonPrimitive().getAsString().replaceAll("\"", ""); return formatter.parse(dateAsString); } catch (Exception ex) { return new Date(); }//from ww w . jav a2s.co m } }); this.context = context; }
From source file:com.denimgroup.threadfix.remote.response.CalendarSerializer.java
License:Mozilla Public License
@Override public Calendar deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(json.getAsJsonPrimitive().getAsLong()); return cal;/*from w w w .ja v a2 s .c o m*/ }
From source file:com.denimgroup.threadfix.remote.response.DateSerializer.java
License:Mozilla Public License
@Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(json.getAsJsonPrimitive().getAsLong()); return cal.getTime(); }
From source file:com.edgebox.eacds.net.CDPostResponse.java
License:Open Source License
public static CDPostResponse build(String json) { CDPostResponse rt = new CDPostResponse(); JsonElement e = new JsonParser().parse(json); rt.json = e.getAsJsonObject();// w w w.j av a2s .c o m rt.success = rt.json.get("success").getAsBoolean(); rt.message = rt.json.get("message").getAsString(); rt.errorTrace = rt.json.get("errorTrace").getAsString(); try { rt.data = rt.json.getAsJsonObject("data").getAsJsonObject(); } catch (java.lang.ClassCastException ex) { rt.data = rt.json.get("data").getAsString(); } JsonElement dt = rt.json.get("data"); if (dt.isJsonNull()) { rt.data = null; } else if (dt.isJsonObject()) { rt.data = dt.getAsJsonObject(); } else { rt.data = dt.getAsJsonPrimitive(); } return rt; }
From source file:com.exsoloscript.challonge.gson.OffsetDateTimeAdapter.java
License:Apache License
@Override public OffsetDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive(); // if provided as String - '2011-12-03T10:15:30+01:00' if (jsonPrimitive.isString()) { return OffsetDateTime.parse(jsonPrimitive.getAsString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME); }//from ww w . jav a 2 s.c o m throw new JsonParseException("Unable to parse OffsetDateTime. DateTime was not provided as string."); }
From source file:com.facebook.buck.json.RawParser.java
License:Apache License
/** * @return One of: String, Boolean, Long, Number, List<Object>, Map<String, Object>. *///from ww w. ja v a 2s . co m @Nullable @VisibleForTesting static Object toRawTypes(JsonElement json) { // Cases are ordered from most common to least common. if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { return interner.intern(primitive.getAsString()); } else if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { Number number = primitive.getAsNumber(); // Number is likely an instance of class com.google.gson.internal.LazilyParsedNumber. if (number.longValue() == number.doubleValue()) { return number.longValue(); } else { return number; } } else { throw new IllegalStateException("Unknown primitive type: " + primitive); } } else if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); List<Object> out = Lists.newArrayListWithCapacity(array.size()); for (JsonElement item : array) { out.add(toRawTypes(item)); } return out; } else if (json.isJsonObject()) { Map<String, Object> out = new LinkedHashMap<>(json.getAsJsonObject().entrySet().size()); for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) { // On a large project, without invoking intern(), we have seen `buck targets` OOM. When this // happened, according to the .hprof file generated using -XX:+HeapDumpOnOutOfMemoryError, // 39.6% of the memory was spent on char[] objects while 14.5% was spent on Strings. // (Another 10.5% was spent on java.util.HashMap$Entry.) Introducing intern() stopped the // OOM from happening. out.put(interner.intern(entry.getKey()), toRawTypes(entry.getValue())); } return out; } else if (json.isJsonNull()) { return null; } else { throw new IllegalStateException("Unknown type: " + json); } }