List of usage examples for com.google.gson JsonPrimitive isString
public boolean isString()
From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTableBase.java
License:Open Source License
/** * Returns the string value represented by the object. * * @param o//from www.j a v a 2 s.co m * @return */ protected String getStringValue(Object o) { String result; if (o instanceof String) { result = (String) o; } else if (o instanceof JsonElement) { JsonElement json = (JsonElement) o; if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { result = primitive.getAsString(); } else { throw new IllegalArgumentException("Object does not represent a string value."); } } else { throw new IllegalArgumentException("Object does not represent a string value."); } } else { throw new IllegalArgumentException("Object does not represent a string value."); } return result; }
From source file:com.nextdoor.bender.operation.json.key.KeyNameOperation.java
License:Apache License
protected void perform(JsonObject obj) { Set<Entry<String, JsonElement>> entries = obj.entrySet(); Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries); for (Entry<String, JsonElement> entry : orgEntries) { JsonElement val = entry.getValue(); obj.remove(entry.getKey());//w ww .j a va2s .c o m String key = entry.getKey().toLowerCase().replaceAll("[ .]", "_"); if (val.isJsonPrimitive()) { JsonPrimitive prim = val.getAsJsonPrimitive(); if (prim.isBoolean()) { obj.add(key + "__bool", val); } else if (prim.isNumber()) { if (prim.toString().contains(".")) { obj.add(key + "__float", val); } else { obj.add(key + "__long", val); } } else if (prim.isString()) { obj.add(key + "__str", val); } } else if (val.isJsonObject()) { obj.add(key, val); perform(val.getAsJsonObject()); } else if (val.isJsonArray()) { obj.add(key + "__arr", val); } } }
From source file:com.qmetry.qaf.automation.gson.GsonObjectDeserializer.java
License:Open Source License
public static Object read(JsonElement in) { if (in.isJsonArray()) { List<Object> list = new ArrayList<Object>(); JsonArray arr = in.getAsJsonArray(); for (JsonElement anArr : arr) { list.add(read(anArr));/*from ww w . j a v a2 s. c o m*/ } return list; } else if (in.isJsonObject()) { Map<String, Object> map = new LinkedTreeMap<String, Object>(); JsonObject obj = in.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet(); for (Map.Entry<String, JsonElement> entry : entitySet) { map.put(entry.getKey(), read(entry.getValue())); } return map; } else if (in.isJsonPrimitive()) { JsonPrimitive prim = in.getAsJsonPrimitive(); if (prim.isBoolean()) { return prim.getAsBoolean(); } else if (prim.isString()) { return prim.getAsString(); } else if (prim.isNumber()) { if (prim.getAsString().contains(".")) return prim.getAsDouble(); else { return prim.getAsLong(); } } } return null; }
From source file:com.ryanantkowiak.jOptionsHouseAPI.JsonUtilities.java
License:Open Source License
/** * Recursively print the contents of a GSON JSON element. * /* w ww . ja v a 2 s . co m*/ * @param element the GSON JSON element to be printed * @param prefix output will be prefixed with this string */ public static void printJson(JsonElement element, String prefix) { if (null == prefix || prefix.isEmpty()) { prefix = ""; } if (null == element || element.isJsonNull()) { System.out.println(prefix + " [null]"); return; } else if (element.isJsonPrimitive()) { JsonPrimitive p = element.getAsJsonPrimitive(); if (p.isBoolean()) { System.out.println(prefix + " [bool=" + p.getAsBoolean() + "]"); } else if (p.isString()) { System.out.println(prefix + " [string='" + p.getAsString() + "']"); } else if (p.isNumber()) { System.out.println(prefix + " [number=" + p.getAsDouble() + "]"); } } else if (element.isJsonArray()) { System.out.println(prefix + " [array]"); for (int i = 0; i < element.getAsJsonArray().size(); ++i) { String newPrefix = prefix + "[" + i + "]"; printJson(element.getAsJsonArray().get(i), newPrefix); } } else if (element.isJsonObject()) { JsonObject obj = element.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); String newPrefix = prefix + "." + key; printJson(value, newPrefix); } } }
From source file:com.seleritycorp.common.base.config.ConfigUtils.java
License:Apache License
/** * Adds a JSON primitive to a Config.//w ww . j ava 2s . c o m * * @param primitive The primitive to add * @param config The config instance to add the primitive to * @param key The key in the config space */ private static void loadJson(JsonPrimitive primitive, ConfigImpl config, String key) { String value = null; if (primitive.isBoolean()) { boolean bool = primitive.getAsBoolean(); value = bool ? "true" : "false"; } else if (primitive.isString()) { value = primitive.getAsString(); } else if (primitive.isNumber()) { value = Double.toString(primitive.getAsDouble()); } config.set(key, value); }
From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java
License:Open Source License
private @CheckForNull Object toSimpleJavaType(JsonElement jsonValue) { if (jsonValue == null) return null; //VR Object value = null;// w w w . j a v a2s .co m if (!jsonValue.isJsonNull()) { if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isBoolean()) { value = Boolean.valueOf(primitive.getAsBoolean()); } else if (primitive.isNumber()) { value = Double.valueOf(primitive.getAsDouble()); } else if (primitive.isString()) { value = primitive.getAsString(); } else { throw UnexpectedException.forUnexpectedCodeBranchExecuted(); } } else if (jsonValue.isJsonArray()) { //This simply does not work (?) JsonArray array = jsonValue.getAsJsonArray(); Object[] result = new Object[array.size()]; for (int i = 0; i < array.size(); i++) { result[i] = toSimpleJavaType(array.get(i)); } value = result; } else if (jsonValue.isJsonObject()) { //This simply does not work (?) //value = getGson().fromJson(jsonValue, Map.class ); JsonObject obj = jsonValue.getAsJsonObject(); Iterator<Entry<String, JsonElement>> properties = obj.entrySet().iterator(); Map<String, Object> result = new HashMap<String, Object>(); while (properties.hasNext()) { Entry<String, JsonElement> property = properties.next(); JsonElement propertyValue = property.getValue(); result.put(property.getKey(), toSimpleJavaType(propertyValue)); } value = result; } else { throw UnexpectedException.forUnexpectedCodeBranchExecuted(); } } return value; }
From source file:com.synflow.cx.internal.instantiation.properties.Specializer.java
License:Open Source License
/** * Returns an IR expression from the given JSON element. * /*from www .j a v a 2s . com*/ * @param json * a JSON element (should be a primitive) * @return an expression, or <code>null</code> */ public Expression transformJson(JsonElement json) { if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isBoolean()) { return eINSTANCE.createExprBool(primitive.getAsBoolean()); } else if (primitive.isNumber()) { return eINSTANCE.createExprInt(primitive.getAsBigInteger()); } else if (primitive.isString()) { return eINSTANCE.createExprString(primitive.getAsString()); } } return null; }
From source file:com.talvish.tales.auth.jwt.TokenManager.java
License:Apache License
/** * Helper method that takes a string segment (e.g. headers, claims) and * base64 decodes, parses out the json and generates a map of the values. * @param theSegment the segment to process * @return the map of values generated from the segment *//* w ww . jav a 2 s. c om*/ private Map<String, Object> processSegment(String theSegment, int theSegmentIndex) { Map<String, Object> outputItems = new HashMap<>(); ClaimDetails claimDetails; String claimName = null; JsonElement claimValue = null; try { JsonObject inputJson = (JsonObject) jsonParser .parse(new String(base64Decoder.decode(theSegment), utf8)); for (Entry<String, JsonElement> entry : inputJson.entrySet()) { claimName = entry.getKey(); claimValue = entry.getValue(); claimDetails = this.claimHandlers.get(claimName); if (claimDetails != null) { outputItems.put(claimName, claimDetails.getTypeAdapter().getFromFormatTranslator().translate(claimValue)); } else if (claimValue.isJsonPrimitive()) { JsonPrimitive primitiveJson = (JsonPrimitive) claimValue; if (primitiveJson.isString()) { outputItems.put(claimName, primitiveJson.getAsString()); } else if (primitiveJson.isNumber()) { outputItems.put(claimName, primitiveJson.getAsNumber()); } else if (primitiveJson.isBoolean()) { outputItems.put(claimName, primitiveJson.getAsBoolean()); } else { throw new IllegalArgumentException(String.format( "Claim '%s' is a primitive json type with value '%s', which has no mechanism for translation.", claimName, claimValue.getAsString())); } } else { throw new IllegalArgumentException(String.format( "Claim '%s' is not a primitive json type with value '%s', which has no mechanism for translation.", claimName, claimValue.getAsString())); } } } catch (JsonParseException e) { throw new IllegalArgumentException( String.format("Segment '%d' contains invalid json.", theSegmentIndex), e); } catch (TranslationException e) { // claim name will be set if we have this exception, if not it will be null and will not cause a problem // but to be safe for the value, which should also be not null, we check so no exceptions are thrown if (claimValue != null) { throw new IllegalArgumentException( String.format("Claim '%s' in segment '%d' contains invalid data '%s'.", claimName, theSegmentIndex, claimValue.getAsString()), e); } else { throw new IllegalArgumentException(String.format( "Claim '%s' in segment '%d' contains invalid data.", claimName, theSegmentIndex), e); } } return outputItems; }
From source file:com.talvish.tales.serialization.json.translators.JsonObjectToPolymorphicObjectTranslator.java
License:Apache License
/** * Translates the received object into the appropriate json representation. * If the object is of the wrong type or the translator used doesn't produce * JsonElements's then a TranslationException will occur. *///from w w w . ja v a 2 s . co m @Override public Object translate(Object anObject) { Object returnValue; if (anObject == null || anObject.equals(JsonNull.INSTANCE)) { returnValue = null; } else { try { // need to extract two things, the "value" and the "value_type" // and if they don't exist then we have a problem JsonObject jsonObject = (JsonObject) anObject; JsonPrimitive valueTypeJson = jsonObject.getAsJsonPrimitive("value_type"); JsonElement valueJson = jsonObject.get("value"); if (valueTypeJson == null || !valueTypeJson.isString()) { throw new TranslationException(String.format("The associate value type is missing.")); } else if (valueJson == null) { throw new TranslationException(String.format("The associate value for type '%s' is missing.", valueTypeJson.getAsString())); } else { String valueTypeString = valueTypeJson.getAsString(); TypeFormatAdapter typeAdapter = typeAdapters.get(valueTypeString); if (typeAdapter == null) { throw new TranslationException(String .format("Json is referring to a type '%s' that isn't supported.", valueTypeString)); } else { returnValue = typeAdapter.getFromFormatTranslator().translate(valueJson); } } // TODO: catch the various gson json exceptions } catch (ClassCastException e) { throw new TranslationException(e); } } return returnValue; }
From source file:com.vmware.xenon.common.serialization.ObjectCollectionTypeConverter.java
License:Open Source License
@Override public Collection<Object> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonArray()) { throw new JsonParseException("Expecting a json array object but found: " + json); }/*from w w w.java 2s . c o m*/ Collection<Object> result; if (TYPE_SET.equals(type)) { result = new HashSet<>(); } else if (TYPE_LIST.equals(type) || TYPE_COLLECTION.equals(type)) { result = new LinkedList<>(); } else { throw new JsonParseException("Unexpected target type: " + type); } JsonArray jsonArray = json.getAsJsonArray(); for (JsonElement entry : jsonArray) { if (entry.isJsonNull()) { result.add(null); } else if (entry.isJsonPrimitive()) { JsonPrimitive elem = entry.getAsJsonPrimitive(); Object value = null; if (elem.isBoolean()) { value = elem.getAsBoolean(); } else if (elem.isString()) { value = elem.getAsString(); } else if (elem.isNumber()) { // We don't know if this is an integer, long, float or double... BigDecimal num = elem.getAsBigDecimal(); try { value = num.longValueExact(); } catch (ArithmeticException e) { value = num.doubleValue(); } } else { throw new RuntimeException("Unexpected value type for json element:" + elem); } result.add(value); } else { // keep JsonElement to prevent stringified json issues result.add(entry); } } return result; }