List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
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 *//*from w w w. j a v a 2s. co m*/ 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.tesla.framework.common.util.json.JSONHelper.java
License:Apache License
@NonNull public static Map<String, String> json2UrlEncodedMap(@NonNull JsonObject data) { Preconditions.checkNotNull(data);/*from ww w . j a v a2 s .c o m*/ Map<String, String> map = new HashMap<>(); Set<Map.Entry<String, JsonElement>> set = data.entrySet(); for (Map.Entry<String, JsonElement> entry : set) { String key = entry.getKey(); if (TextUtils.isEmpty(key)) { continue; } JsonElement value = entry.getValue(); if (value == null) { continue; } String content = value.isJsonPrimitive() ? value.getAsString() : value.toString(); try { map.put(key, URLEncoder.encode(content, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } } return map; }
From source file:com.tesla.framework.common.util.json.JSONHelper.java
License:Apache License
@NonNull public static Map<String, String> json2QueryMap(@NonNull JsonObject data) { Preconditions.checkNotNull(data);/* w ww . jav a2s. c om*/ Map<String, String> map = new HashMap<>(); Set<Map.Entry<String, JsonElement>> set = data.entrySet(); for (Map.Entry<String, JsonElement> entry : set) { String key = entry.getKey(); if (TextUtils.isEmpty(key)) { continue; } JsonElement value = entry.getValue(); if (value == null) { continue; } String content = value.isJsonPrimitive() ? value.getAsString() : value.toString(); map.put(key, content); } return map; }
From source file:com.torben.androidchat.JSONRPC.client.JsonRpcInvoker.java
License:Apache License
private Object invoke(String handleName, HttpJsonRpcClientTransport transport, Method method, Object[] args) throws Throwable { int id = rand.nextInt(Integer.MAX_VALUE); String methodName = handleName + "." + method.getName(); JsonObject req = new JsonObject(); req.addProperty("id", id); req.addProperty("method", methodName); JsonArray params = new JsonArray(); if (args != null) { for (Object o : args) { params.add(gson.toJsonTree(o)); }/* ww w . j a v a2 s . c o m*/ } req.add("params", params); String requestData = req.toString(); LOG.debug("JSON-RPC >> {}", requestData); //Log.v("JSON-RPC >> {}", requestData); String responseData = null; responseData = transport.threadedCall(requestData); //Log.v("Invoker", "respondMSG: "+responseData); JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData)); JsonElement result = resp.get("result"); JsonElement error = resp.get("error"); if (error != null && !error.isJsonNull()) { if (error.isJsonPrimitive()) { throw new JsonRpcRemoteException(error.getAsString()); } else if (error.isJsonObject()) { JsonObject o = error.getAsJsonObject(); Integer code = (o.has("code") ? o.get("code").getAsInt() : null); String message = (o.has("message") ? o.get("message").getAsString() : null); String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString() : o.get("data").getAsString()) : null); throw new JsonRpcRemoteException(code, message, data); } else { throw new JsonRpcRemoteException("unknown error, data = " + error.toString()); } } if (method.getReturnType() == void.class) { return null; } return gson.fromJson(result.toString(), method.getReturnType()); }
From source file:com.tsc9526.monalisa.orm.tools.converters.impl.ArrayTypeConversion.java
License:Open Source License
protected Object convertJsonToArray(JsonArray array, Class<?> type) { Object value = null;/* www . j a v a 2s . c o m*/ if (type == int[].class) { int[] iv = new int[array.size()]; for (int i = 0; i < array.size(); i++) { JsonElement e = array.get(i); iv[i] = e.getAsInt(); } value = iv; } else if (type == float[].class) { float[] iv = new float[array.size()]; for (int i = 0; i < array.size(); i++) { JsonElement e = array.get(i); iv[i] = e.getAsFloat(); } value = iv; } else if (type == long[].class) { long[] iv = new long[array.size()]; for (int i = 0; i < array.size(); i++) { JsonElement e = array.get(i); iv[i] = e.getAsLong(); } value = iv; } else if (type == double[].class) { double[] iv = new double[array.size()]; for (int i = 0; i < array.size(); i++) { JsonElement e = array.get(i); iv[i] = e.getAsDouble(); } value = iv; } else {//String[] String[] iv = new String[array.size()]; for (int i = 0; i < array.size(); i++) { JsonElement e = array.get(i); if (e.isJsonPrimitive()) { iv[i] = e.getAsString(); } else { iv[i] = e.toString(); } } value = iv; } return value; }
From source file:com.tsc9526.monalisa.tools.json.MelpJson.java
License:Open Source License
private static Object toObject(JsonElement e) { if (e == null || e.isJsonNull()) { return null; } else if (e.isJsonPrimitive()) { return primitive((JsonPrimitive) e); } else if (e.isJsonObject()) { return parseToDataMap(e.getAsJsonObject()); } else if (e.isJsonArray()) { List<Object> list = new ArrayList<Object>(); JsonArray array = (JsonArray) e; for (int i = 0; i < array.size(); i++) { JsonElement je = array.get(i); Object v = toObject(je); list.add(v);/*from w w w . j av a 2 s. co m*/ } return list; } else { return e; } }
From source file:com.twitter.sdk.android.core.models.BindingValuesAdapter.java
License:Apache License
Object getValue(JsonObject obj, JsonDeserializationContext context) { final JsonElement typeObj = obj.get(TYPE_MEMBER); if (typeObj == null || !typeObj.isJsonPrimitive()) { return null; }// w w w. j a v a2 s.c o m switch (typeObj.getAsString()) { case STRING_TYPE: return context.deserialize(obj.get(TYPE_VALUE_MEMBER), String.class); case IMAGE_TYPE: return context.deserialize(obj.get(IMAGE_VALUE_MEMBER), ImageValue.class); case USER_TYPE: return context.deserialize(obj.get(USER_VALUE_MEMBER), UserValue.class); case BOOLEAN_TYPE: return context.deserialize(obj.get(BOOLEAN_MEMBER), Boolean.class); default: return null; } }
From source file:com.uprizer.sensearray.freetools.json.GsonPrettyPrinter.java
License:Open Source License
private List<String> toStringList(final JsonElement je) { 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); } else if (je.isJsonNull()) { return Collections.singletonList("null"); } else {/* w w w.j ava 2 s .com*/ throw new RuntimeException("Unsupported Json element: " + je.getClass().getName()); } }
From source file:com.vmware.dcp.common.serialization.ObjectMapTypeConverter.java
License:Open Source License
@Override public Map<String, Object> deserialize(JsonElement json, Type unused, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("The json element is not valid"); }/*from w w w .ja v a2 s .c om*/ Map<String, Object> result = new HashMap<String, Object>(); JsonObject jsonObject = json.getAsJsonObject(); for (Entry<String, JsonElement> entry : jsonObject.entrySet()) { String key = entry.getKey(); JsonElement element = entry.getValue(); if (element.isJsonObject()) { result.put(key, element.toString()); } else if (element.isJsonNull()) { result.put(key, null); } else if (element.isJsonPrimitive()) { result.put(key, element.getAsString()); } else { throw new JsonParseException("The json element is not valid for key:" + key + " value:" + element); } } return result; }
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 . j a va 2 s . co 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; }