List of usage examples for com.google.gson JsonElement getAsJsonPrimitive
public JsonPrimitive getAsJsonPrimitive()
From source file:com.flipkart.android.proteus.toolbox.Utils.java
License:Apache License
public static JsonElement merge(JsonElement oldJson, JsonElement newJson, boolean useCopy, Gson gson) { JsonElement newDataElement;//from w w w .j ava 2s. c o m JsonArray oldArray; JsonArray newArray; JsonElement oldArrayItem; JsonElement newArrayItem; JsonObject oldObject; if (oldJson == null || oldJson.isJsonNull()) { return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson; } if (newJson == null || newJson.isJsonNull()) { newJson = JsonNull.INSTANCE; return newJson; } if (newJson.isJsonPrimitive()) { JsonPrimitive value; if (!useCopy) { return newJson; } if (newJson.getAsJsonPrimitive().isBoolean()) { value = new JsonPrimitive(newJson.getAsBoolean()); } else if (newJson.getAsJsonPrimitive().isNumber()) { value = new JsonPrimitive(newJson.getAsNumber()); } else if (newJson.getAsJsonPrimitive().isString()) { value = new JsonPrimitive(newJson.getAsString()); } else { value = newJson.getAsJsonPrimitive(); } return value; } if (newJson.isJsonArray()) { if (!oldJson.isJsonArray()) { return useCopy ? gson.fromJson(newJson, JsonArray.class) : newJson; } else { oldArray = oldJson.getAsJsonArray(); newArray = newJson.getAsJsonArray(); if (oldArray.size() > newArray.size()) { while (oldArray.size() > newArray.size()) { oldArray.remove(oldArray.size() - 1); } } for (int index = 0; index < newArray.size(); index++) { if (index < oldArray.size()) { oldArrayItem = oldArray.get(index); newArrayItem = newArray.get(index); oldArray.set(index, merge(oldArrayItem, newArrayItem, useCopy, gson)); } else { oldArray.add(newArray.get(index)); } } } } else if (newJson.isJsonObject()) { if (!oldJson.isJsonObject()) { return useCopy ? gson.fromJson(newJson, JsonObject.class) : newJson; } else { oldObject = oldJson.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : newJson.getAsJsonObject().entrySet()) { newDataElement = merge(oldObject.get(entry.getKey()), entry.getValue(), useCopy, gson); oldObject.add(entry.getKey(), newDataElement); } } } else { return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson; } return oldJson; }
From source file:com.flipkart.polyguice.config.JsonConfiguration.java
License:Apache License
private void flatten(String prefix, JsonElement element) { if (element.isJsonPrimitive()) { JsonPrimitive jsonPrim = element.getAsJsonPrimitive(); if (jsonPrim.isBoolean()) { configTab.put(prefix, jsonPrim.getAsBoolean()); } else if (jsonPrim.isNumber()) { configTab.put(prefix, jsonPrim.getAsNumber()); } else if (jsonPrim.isString()) { configTab.put(prefix, jsonPrim.getAsString()); }//from ww w .j a va2 s .c o m } else if (element.isJsonObject()) { JsonObject jsonObj = element.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) { String prefix1 = ((prefix != null) ? prefix + "." : "") + entry.getKey(); flatten(prefix1, entry.getValue()); } } }
From source file:com.frontier45.flume.sink.elasticsearch2.ElasticSearchLogStashEventSerializer.java
License:Apache License
private Object getValue(JsonElement obj) { JsonPrimitive jp = obj.getAsJsonPrimitive(); if (jp.isBoolean()) { return jp.getAsBoolean(); } else if (jp.isNumber()) { String value = jp.getAsString(); if (value.indexOf(".") > 0) { return jp.getAsDouble(); } else {/*from w w w . java 2 s.c o m*/ return jp.getAsLong(); } } else if (jp.isString()) { return jp.getAsString(); } return obj; }
From source file:com.getperka.flatpack.codexes.BooleanCodex.java
License:Apache License
@Override public Boolean readNotNull(JsonElement element, DeserializationContext context) { return element.getAsJsonPrimitive().isNumber() ? element.getAsNumber().intValue() != 0 : element.getAsBoolean();//from w ww . j a v a 2 s . c o m }
From source file:com.getperka.flatpack.codexes.CharacterCodex.java
License:Apache License
@Override public Character readNotNull(JsonElement element, DeserializationContext context) throws Exception { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); // Treat a number as a BMP code point if (primitive.isNumber()) { return (char) primitive.getAsInt(); } else {/*from ww w. j a v a 2 s . c o m*/ return primitive.getAsCharacter(); } } throw new IllegalArgumentException("Cannot convert " + element.toString() + " to a char"); }
From source file:com.getperka.flatpack.codexes.DateCodex.java
License:Apache License
@Override public D readNotNull(JsonElement element, DeserializationContext context) throws Exception { if (element.isJsonPrimitive()) { long instant; JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isNumber()) { instant = primitive.getAsLong(); } else {/*w w w. java 2 s .c om*/ instant = ISODateTimeFormat.dateTimeParser().parseMillis(primitive.getAsString()); } return constructor.newInstance(instant); } throw new IllegalArgumentException("Could not parse " + element.toString() + " as a date value"); }
From source file:com.getperka.flatpack.codexes.DynamicCodex.java
License:Apache License
/** * Attempt to infer the type from the JsonElement presented. * <ul>/*from w w w . ja va 2 s . c om*/ * <li>boolean -> {@link Boolean} * <li>number -> {@link BigDecimal} * <li>string -> {@link HasUuid} or {@link String} * <li>array -> {@link ListCodex} * <li>object -> {@link StringMapCodex} * </ul> */ @Override public Object readNotNull(JsonElement element, DeserializationContext context) throws Exception { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { // Always return numbers as BigDecimals for consistency return primitive.getAsBigDecimal(); } else { String value = primitive.getAsString(); // Interpret UUIDs as entity references if (UUID_PATTERN.matcher(value).matches()) { UUID uuid = UUID.fromString(value); HasUuid entity = context.getEntity(uuid); if (entity != null) { return entity; } } return value; } } else if (element.isJsonArray()) { return listCodex.get().readNotNull(element, context); } else if (element.isJsonObject()) { return mapCodex.get().readNotNull(element, context); } context.fail(new UnsupportedOperationException("Cannot infer data type for " + element.toString())); return null; }
From source file:com.github.francescojo.gsondbg.GsonDebuggable.java
private void inspectJsonObject(JsonObject jsonObject, Class<?> klass) { Map<String, Field> mappingInfo = new HashMap<String, Field>(); for (Field classField : klass.getDeclaredFields()) { Annotation[] annotations = classField.getAnnotations(); if (null == annotations || 0 == annotations.length) { mappingInfo.put(classField.getName(), classField); } else {/*from www .j a v a 2 s . com*/ for (Annotation annotation : annotations) { if (annotation instanceof SerializedName) { String customName = ((SerializedName) annotation).value(); mappingInfo.put(customName, classField); /* * FIXME: alternate() is introduced in Gson 2.4. Safe to delete if your Gson is lower than 2.4. */ try { String[] alternateNames = ((SerializedName) annotation).alternate(); for (String alternateName : alternateNames) { mappingInfo.put(alternateName, classField); } } catch (NoSuchMethodError ignore) { } } } } } for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (!mappingInfo.containsKey(key)) { /* * Gson ignores fields that are not found in json by default - following same rule in here. */ continue; } Field javaField = mappingInfo.get(key); Class<?> javaType = javaField.getType(); if (WellKnownTypeCastingRules.isWellKnown(javaType)) { if (!(value instanceof JsonPrimitive)) { log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }", javaField.getDeclaringClass().getName(), javaField.getName(), javaField.getType().getCanonicalName(), key, value); continue; } WellKnownTypeCastingRules rule = WellKnownTypeCastingRules.byJavaType(javaType); JsonPrimitive primitive = value.getAsJsonPrimitive(); if (rule.isAcceptable(primitive)) { continue; } log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }", javaField.getDeclaringClass().getName(), javaField.getName(), javaField.getType().getCanonicalName(), key, value); } else if (javaType.isArray()) { try { gson.fromJson(value, javaType); } catch (JsonSyntaxException e) { log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }", javaField.getDeclaringClass().getName(), javaField.getName(), javaField.getType().getCanonicalName(), key, value); } } else if (value.isJsonObject()) { inspectJsonObject(value.getAsJsonObject(), javaType); } } }
From source file:com.github.GsonPrettyPrinter.java
License:Open Source License
private List<String> toStringList(final JsonElement je) { if (je == null || je.isJsonNull()) return new ArrayList<String>(Arrays.asList(new String[] { "null" })); if (je.isJsonPrimitive()) return Collections.singletonList(je.getAsJsonPrimitive().toString()); if (je.isJsonArray()) { final JsonArray jsonArray = je.getAsJsonArray(); return arrayToStringList(jsonArray); } else if (je.isJsonObject()) { final JsonObject jsonObject = je.getAsJsonObject(); return objectToStringList(jsonObject); }/*from w ww.j av a 2 s . com*/ throw new RuntimeException("Unsupported Json element: " + je.getClass().getName()); }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
License:Apache License
private String getString(JsonObject responseObject, String key) { if (responseObject.has(key)) { JsonElement element = responseObject.get(key); if (element.isJsonPrimitive() && element.getAsJsonPrimitive().isString()) { return element.getAsString(); } else {//from w w w. jav a 2 s .c o m logger.warn("The {} property (={}) is not a string in document: {}", new Object[] { key, element, responseObject }); } } else { logger.warn("The key {} is missing from document: {}", key, responseObject); } return ""; }