List of usage examples for com.google.gson JsonSyntaxException JsonSyntaxException
public JsonSyntaxException(Throwable cause)
From source file:com.ecwid.mailchimp.internal.gson.MailChimpObjectTypeAdapter.java
License:Apache License
@Override public MailChimpObject read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull();/* ww w . ja v a 2s. c o m*/ return null; } MailChimpObject result; try { result = constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Failed to invoke " + constructor + " with no args", e); } in.beginObject(); while (in.hasNext()) { final String key; if (in.peek() == JsonToken.NAME) { key = in.nextName(); } else { key = in.nextString(); } final Object value; Type valueType = result.getReflectiveMappingTypes().get(key); if (valueType != null) { value = gson.getAdapter(TypeToken.get(valueType)).read(in); } else { if (in.peek() == JsonToken.BEGIN_OBJECT) { value = gson.getAdapter(MailChimpObject.class).read(in); } else if (in.peek() == JsonToken.BEGIN_ARRAY) { value = readList(in); } else { value = gson.getAdapter(Object.class).read(in); } } if (result.put(key, value) != null) { throw new JsonSyntaxException("duplicate key: " + key); } } in.endObject(); return result; }
From source file:com.gilecode.yagson.adapters.AdapterUtils.java
License:Apache License
/** * Returns the fields which needs to be saved for the special container object (map, set or collection) except * of the standard collection entries, if these fields have non-default values in the actual serialized objects. * <p/>/* w w w . ja va 2 s . co m*/ * For example, non-null comparators in maps/sets need to be saved. * @param containerClass the class containing the reflective fields; e.g. HashMap.class * @param defaultObjectProvider the provider of the default container object for checking the default values * @param fieldClassesToFind the field classes to find * @param exceptClasses the field classes to skip from search */ @SuppressWarnings("unchecked") public static <T> Map<String, FieldInfo> buildReflectiveFieldsInfo(Gson gson, Class<? extends T> containerClass, ObjectProvider<? extends T> defaultObjectProvider, Iterable<Class<?>> fieldClassesToFind, Iterable<Class<?>> exceptClasses) { if (!gson.getTypeInfoPolicy().isEnabled()) { // require type info for correct work return Collections.emptyMap(); } Map<String, FieldInfo> result = new TreeMap<String, FieldInfo>(); List<Field> fields = TypeUtils.findFields(containerClass, true, fieldClassesToFind, exceptClasses); if (fields.isEmpty()) { return result; } T defaultInstance = defaultObjectProvider.get(); for (Field f : fields) { String fname = f.getName(); if (result.containsKey(fname)) { // skip duplicate names, get/set only 'latest' versions (closest to the actual class) continue; } f.setAccessible(true); Object defaultValue; try { defaultValue = f.get(defaultInstance); } catch (IllegalAccessException e) { throw new JsonSyntaxException( "Failed to get the Map reflective field value; mapType=" + containerClass + "; field=" + f); } Class<?> defaultFieldClass = defaultValue == null ? f.getType() : defaultValue.getClass(); TypeAdapter<Object> fieldAdapter = new DefaultTypeAdapterRuntimeWrapper(gson, defaultFieldClass, f.getGenericType()); result.put(fname, new FieldInfo(f, defaultValue, fieldAdapter)); } return result; }
From source file:com.gilecode.yagson.adapters.AdapterUtils.java
License:Apache License
public static void readAndSetReflectiveField(Object instance, String fname, Map<String, FieldInfo> reflectiveFields, JsonReader in, ReadContext ctx, String valPathElement) throws IOException { FieldInfo fieldInfo = reflectiveFields.get(fname); if (fieldInfo == null) { throw new JsonSyntaxException( "The " + instance.getClass() + " does not have serializable reflective field '" + fname + "'"); }//from w w w.j a v a2s . c om // read value using the corresponding type adapter Object fieldValue = ctx.doRead(in, fieldInfo.getFieldAdapter(), valPathElement); // try set the field try { fieldInfo.getField().set(instance, fieldValue); } catch (IllegalAccessException e) { throw new JsonSyntaxException("Failed to set the reflective field value; instanceClass=" + instance.getClass() + "; field=" + fieldInfo.getField() + "; value=" + fieldValue); } }
From source file:com.gilecode.yagson.refs.impl.PlaceholderUtils.java
License:Apache License
@SuppressWarnings("unchecked") private static <T> void tryResolveFieldPlaceholder(Field fieldToResolve, Map<Field, ReferencePlaceholder> placeholders, Map<String, ? extends HasField> fieldsByName, T instance, Set<Field> unresolvedFields, Set<Field> hashFields, Set<Field> deferredReferencesFields) throws IOException { final ReferencePlaceholder placeholder = placeholders.get(fieldToResolve); assert placeholder != null; if (placeholder instanceof HashReferencePlaceholder) { hashFields.add(fieldToResolve);// w w w . j a v a 2 s . co m } else if (placeholder instanceof FieldReferencePlaceholder) { FieldReferencePlaceholder fieldRefPlaceholder = (FieldReferencePlaceholder) placeholder; String referencedFieldName = fieldRefPlaceholder.getReferencedFieldName(); if (!fieldRefPlaceholder.isResolved()) { HasField fieldProvider = fieldsByName.get(referencedFieldName); if (fieldProvider == null) { throw new JsonSyntaxException( "No field found for the serialization name '" + referencedFieldName + "'"); } fieldRefPlaceholder.setReferencedField(fieldProvider.getField()); } Field referencedField = fieldRefPlaceholder.getReferencedField(); // if there are no unresolved placeholders at the referenced field, we can use its value now ReferencePlaceholder chainedPlaceholder = placeholders.get(referencedField); Object referencedValue; if (chainedPlaceholder != null) { if (chainedPlaceholder.getActualObject() == null) { // not resolved yet, check if met in processed sets if (unresolvedFields.remove(referencedField)) { // recursively process referenced placeholder tryResolveFieldPlaceholder(fieldToResolve, placeholders, fieldsByName, instance, unresolvedFields, hashFields, deferredReferencesFields); } if (chainedPlaceholder.getActualObject() == null) { // still not resolved - must be either hash or deferred if (hashFields.contains(referencedField)) { // treat as hash reference hashFields.add(referencedField); } else if (deferredReferencesFields.contains(referencedField)) { // chain to the deferred placeholder deferredReferencesFields.add(referencedField); chainedPlaceholder.registerUse(new PlaceholderUse() { public void applyActualObject(Object actualObject) throws IOException { placeholder.applyActualObject(actualObject); } }); } else { throw new IllegalStateException( "The placeholder is expected to be already processed: " + chainedPlaceholder); } return; } } referencedValue = chainedPlaceholder.getActualObject(); assert referencedValue != null; } else { try { referencedValue = referencedField.get(instance); } catch (IllegalAccessException e) { throw new JsonSyntaxException( "Failed to get the referenced reflective field value; field=" + referencedField); } } fieldRefPlaceholder.applyActualObject(referencedValue); } else { deferredReferencesFields.add(fieldToResolve); } }
From source file:com.gilecode.yagson.refs.impl.ReferencesNoneModeContext.java
License:Apache License
public <T> T getReferencedObject(String reference) throws IOException { throw new JsonSyntaxException("The reference cannot be read, as the current policy is ReferencesPolicy." + ReferencesPolicy.DISABLED + ": '" + reference + "'"); }
From source file:com.gilecode.yagson.types.TypeUtils.java
License:Apache License
private static Type readTypeAdvice(JsonReader in) throws IOException { in.beginObject();//w ww . j a v a 2 s . co m if (!in.hasNext()) { throw new JsonSyntaxException("BEGIN_OBJECT is not expected at path " + in.getPath()); } String name = in.nextName(); if (!name.equals("@type")) { throw new JsonSyntaxException("@type is expected at path " + in.getPath()); } return readTypeAdviceAfterTypeField(in); }
From source file:com.gilecode.yagson.types.TypeUtils.java
License:Apache License
private static Type readTypeAdviceAfterTypeField(JsonReader in) throws IOException { // Check whether next tokens are type advise, fail if not String advisedTypeStr = in.nextString(); String advisedClassStr = advisedTypeStr; int i = advisedTypeStr.indexOf('<'); if (i >= 0) { if (!advisedTypeStr.endsWith(">")) { throw new JsonSyntaxException("Incorrect advised type: '" + advisedTypeStr + "'"); }//from w w w .ja v a 2 s . c om advisedClassStr = advisedTypeStr.substring(0, i).trim(); String parametersStr = advisedTypeStr.substring(i + 1, advisedTypeStr.length() - 1).trim(); String[] parameters = parametersStr.split(","); Type[] parameterTypes = new Type[parameters.length]; boolean hasParameterTypes = false; for (int j = 0; j < parameters.length; j++) { Type type = toType(parameters[j].trim()); parameterTypes[j] = type; if (type != unknownType) { hasParameterTypes = true; } } if (hasParameterTypes) { Class advisedClass = (Class) toType(advisedClassStr); return $Gson$Types.newParameterizedTypeWithOwner(advisedClass.getEnclosingClass(), advisedClass, parameterTypes); } } return toType(advisedClassStr); }
From source file:com.gilecode.yagson.types.TypeUtils.java
License:Apache License
private static boolean consumeValueField(JsonReader in) throws IOException { if (!in.hasNext()) { // no @val means actually null value, e.g. skipped by serialization return false; }/*from ww w . j a v a 2 s . c o m*/ String name = in.nextName(); if (!name.equals("@val")) { throw new JsonSyntaxException("Only @type and @val fields are expected at the type advice " + "objects at path " + in.getPath()); } return true; }
From source file:com.gilecode.yagson.types.TypeUtils.java
License:Apache License
public static void initEnumMapKeyType(EnumMap<?, ?> instance, Class<?> keyType) { if (!keyType.isEnum()) { throw new JsonSyntaxException("Only enum keys are allowed for EnumMap, but got " + keyType); }//from w w w. jav a2 s . c om EnumMap otherInstance = new EnumMap(keyType); copyFields(instance, otherInstance, EnumMap.class, "keyType", "keyUniverse", "vals"); }
From source file:com.github.xose.persona.verifier.VerifyResultParser.java
License:Apache License
public final static VerifyResult fromJSONString(String input) { JsonObject response = parser.parse(input).getAsJsonObject(); String status = response.get("status").getAsString(); if ("okay".equals(status)) { String email = response.get("email").getAsString(); String audience = response.get("audience").getAsString(); Date expires = new Date(response.get("expires").getAsLong()); String issuer = response.get("issuer").getAsString(); return new VerifyResult(email, audience, expires, issuer); } else if ("failure".equals(status)) { String reason = response.get("reason").getAsString(); return new VerifyResult(reason); }/*from w w w. ja v a 2 s . c om*/ throw new JsonSyntaxException("Invalid status"); }