Java Code Examples for com.google.gson.annotations.SerializedName#value()

The following examples show how to use com.google.gson.annotations.SerializedName#value() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeAdapters.java    From gson with Apache License 2.0 6 votes vote down vote up
public EnumTypeAdapter(Class<T> classOfT) {
  try {
    for (T constant : classOfT.getEnumConstants()) {
      String name = constant.name();
      SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class);
      if (annotation != null) {
        name = annotation.value();
        for (String alternate : annotation.alternate()) {
          nameToConstant.put(alternate, constant);
        }
      }
      nameToConstant.put(name, constant);
      constantToName.put(constant, name);
    }
  } catch (NoSuchFieldException e) {
    throw new AssertionError(e);
  }
}
 
Example 2
Source File: JsonEntityParser.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Get's the class' id property name
 *
 * @param clazz
 * @return Id Property name
 */
@SuppressWarnings("rawtypes")
private static String getIdPropertyName(Class clazz) {
    // Search for annotation called id, regardless case
    for (Field field : clazz.getDeclaredFields()) {

        SerializedName serializedName = field.getAnnotation(SerializedName.class);
        if (serializedName != null && serializedName.value().equalsIgnoreCase("id")) {
            return serializedName.value();
        } else if (field.getName().equalsIgnoreCase("id")) {
            return field.getName();
        }
    }

    // Otherwise, return empty
    return "";
}
 
Example 3
Source File: Mapper.java    From Morpheus with MIT License 6 votes vote down vote up
/**
 * Get the annotated relationship names.
 *
 * @param clazz Class for annotation.
 * @return List of relationship names.
 */
private HashMap<String, String> getRelationshipNames(Class clazz) {
  HashMap<String, String> relationNames = new HashMap<>();
  for (Field field : clazz.getDeclaredFields()) {
    String fieldName = field.getName();
    for (Annotation annotation : field.getDeclaredAnnotations()) {
      if (annotation.annotationType() == SerializedName.class) {
        SerializedName serializeName = (SerializedName)annotation;
        fieldName = serializeName.value();
      }
      if (annotation.annotationType() == Relationship.class) {
        Relationship relationshipAnnotation = (Relationship)annotation;
        relationNames.put(relationshipAnnotation.value(), fieldName);
      }
    }
  }

  return relationNames;
}
 
Example 4
Source File: DebugEnumTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
public DebugEnumTypeAdapter(Class<T> clazz) {
	try {
		for (T constant : clazz.getEnumConstants()) {
			String name = constant.name();
			String serializedForm = getSerializedForm(name);
			// Like default gson, allow overriding names with SerializedName
			SerializedName annotation = clazz.getField(name).getAnnotation(SerializedName.class);
			if (annotation != null) {
				serializedForm = annotation.value();
				for (String alternate : annotation.alternate()) {
					serializedFormToEnum.put(alternate, constant);
				}
			}
			serializedFormToEnum.put(serializedForm, constant);
			enumToSerializedForm.put(constant, serializedForm);
		}
	} catch (NoSuchFieldException e) {
		throw new AssertionError(e);
	}
}
 
Example 5
Source File: DocumentRegistry.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String serializedName(Member member) {
    if(member instanceof AnnotatedElement) {
        SerializedName nameAnnot = ((AnnotatedElement) member).getAnnotation(SerializedName.class);
        if(nameAnnot != null) return nameAnnot.value();
    }
    return member.getName();
}
 
Example 6
Source File: TypeAdapters.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
public EnumTypeAdapter(Class<T> classOfT) {
  try {
    for (T constant : classOfT.getEnumConstants()) {
      String name = constant.name();
      SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class);
      if (annotation != null) {
        name = annotation.value();
      }
      nameToConstant.put(name, constant);
      constantToName.put(constant, name);
    }
  } catch (NoSuchFieldException e) {
    throw new AssertionError();
  }
}
 
Example 7
Source File: GsonParser.java    From typescript-generator with MIT License 5 votes vote down vote up
private BeanModel parseBean(SourceType<Class<?>> sourceClass) {
    final List<PropertyModel> properties = new ArrayList<>();
    Class<?> cls = sourceClass.type;
    while (cls != null) {
        for (Field field : cls.getDeclaredFields()) {
            String name = field.getName();
            SerializedName serializedName = field.getAnnotation(SerializedName.class);
            if (serializedName != null) {
                name = serializedName.value();
            }
            properties.add(new PropertyModel(name, field.getGenericType(), false, field, null, null, null));
            addBeanToQueue(new SourceType<>(field.getGenericType(), sourceClass.type, name));
        }
        cls = cls.getSuperclass();
    }

    final Type superclass = sourceClass.type.getGenericSuperclass() == Object.class ? null
            : sourceClass.type.getGenericSuperclass();
    if (superclass != null) {
        addBeanToQueue(new SourceType<>(superclass, sourceClass.type, "<superClass>"));
    }
    final List<Type> interfaces = Arrays.asList(sourceClass.type.getGenericInterfaces());
    for (Type aInterface : interfaces) {
        addBeanToQueue(new SourceType<>(aInterface, sourceClass.type, "<interface>"));
    }
    return new BeanModel(sourceClass.type, superclass, null, null, null, interfaces, properties, null);
}
 
Example 8
Source File: ReflectiveTypeAdapterFactory.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private String a(Field field)
{
    SerializedName serializedname = (SerializedName)field.getAnnotation(com/google/gson/annotations/SerializedName);
    if (serializedname == null)
    {
        return b.translateName(field);
    } else
    {
        return serializedname.value();
    }
}
 
Example 9
Source File: Mapper.java    From Morpheus with MIT License 5 votes vote down vote up
/**
 * Maps the attributes of json to the object.
 *
 * @param object Object of the class.
 * @param attributesJsonObject Attributes object inside the data node.
 * @return Object with mapped fields.
 */
public Resource mapAttributes(Resource object, JSONObject attributesJsonObject) {
  if (attributesJsonObject == null) {
    return object;
  }

  for (Field field : object.getClass().getDeclaredFields()) {
    // get the right attribute name
    String jsonFieldName = field.getName();
    boolean isRelation = false;
    for (Annotation annotation : field.getAnnotations()) {
      if (annotation.annotationType() == SerializedName.class) {
        SerializedName serializeName = (SerializedName) annotation;
        jsonFieldName = serializeName.value();
      }
      if (annotation.annotationType() == Relationship.class) {
        isRelation = true;
      }
    }

    if (isRelation) {
      continue;
    }

    attributeMapper.mapAttributeToObject(object, attributesJsonObject, field, jsonFieldName);
  }

  return object;
}
 
Example 10
Source File: Serializer.java    From Morpheus with MIT License 5 votes vote down vote up
/**
 * Return objects fields as dictionary with fieldName as key
 * and fieldObject as value.
 *
 * @param resource A morpheus resource.
 * @return hashMap of field names and values.
 */
public HashMap<String, Object> getFieldsAsDictionary(Resource resource) {
  HashMap<String, Object> fieldDict = null;

  for (Field field : resource.getClass().getDeclaredFields()) {
    String fieldName = null;

    if (field.isAnnotationPresent(Relationship.class)) {
      continue;
    }

    Object fieldValue = null;
    try {
      field.setAccessible(true);
      fieldValue = field.get(resource);
      if (fieldValue == null) {
        continue;
      }
    } catch (IllegalAccessException e) {
      Logger.debug("Cannot access field: " + fieldName + ".");
    }

    if (field.isAnnotationPresent(SerializedName.class)) {
      Annotation annotation = field.getAnnotation(SerializedName.class);
      SerializedName serializeName = (SerializedName) annotation;
      fieldName = serializeName.value();
    } else {
      fieldName = field.getName();
    }

    if (fieldDict == null) {
      fieldDict = new HashMap<>();
    }

    fieldDict.put(fieldName, fieldValue);
  }

  return fieldDict;
}
 
Example 11
Source File: BaseModel.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
public BaseModel validate() {
    for (Field f : getProperties()) {
        String jsonFieldName = f.getName();
        SerializedName serializedNameAnnotation = f.getAnnotation(SerializedName.class);
        if (serializedNameAnnotation != null && !isBlank(serializedNameAnnotation.value())) {
            jsonFieldName = serializedNameAnnotation.value();
        }

        Object fieldValue;
        try {
            f.setAccessible(true);
            fieldValue = f.get(this);
            if (fieldValue == null && f.getAnnotation(RequiredField.class) != null) {
                throw new IllegalArgumentException(
                        String.format("%s: The mandatory field '%s' is not present in JSON",
                                getClass().getSimpleName(), jsonFieldName));
            }
        } catch (IllegalAccessException ign) {
            continue;
        }

        if (fieldValue == null) {
            continue;
        }

        if (fieldValue instanceof BaseModel) {
            ((BaseModel) fieldValue).validate();
        } else if (fieldValue instanceof List) {
            validateList((List<?>) fieldValue);
        }
    }
    return this;
}
 
Example 12
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public EnumTypeAdapter(Class<T> classOfT) {
    try {
        for (T constant : (Enum[]) classOfT.getEnumConstants()) {
            String name = constant.name();
            SerializedName annotation = (SerializedName) classOfT.getField(name).getAnnotation(SerializedName.class);
            if (annotation != null) {
                name = annotation.value();
            }
            this.nameToConstant.put(name, constant);
            this.constantToName.put(constant, name);
        }
    } catch (NoSuchFieldException e) {
        throw new AssertionError();
    }
}
 
Example 13
Source File: EnumTypeAdapter.java    From IridiumSkyblock with GNU General Public License v2.0 5 votes vote down vote up
public EnumTypeAdapter(Class<T> classOfT) {
    try {
        for (T constant : classOfT.getEnumConstants()) {
            String name = constant.name();
            SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class);
            if (annotation != null) {
                name = annotation.value();
            }
            nameToConstant.put(name, constant);
            constantToName.put(constant, name);
        }
    } catch (NoSuchFieldException e) {
        // ignore since it could be a modified enum
    }
}
 
Example 14
Source File: GsonCompatibilityMode.java    From java with MIT License 4 votes vote down vote up
@Override
protected JsonProperty getJsonProperty(Annotation[] annotations) {
    JsonProperty jsoniterObj = super.getJsonProperty(annotations);
    if (jsoniterObj != null) {
        return jsoniterObj;
    }
    final SerializedName gsonObj = getAnnotation(
            annotations, SerializedName.class);
    if (gsonObj == null) {
        return null;
    }
    return new JsonProperty() {

        @Override
        public String value() {
            return "";
        }

        @Override
        public String[] from() {
            return new String[]{gsonObj.value()};
        }

        @Override
        public String[] to() {
            return new String[]{gsonObj.value()};
        }

        @Override
        public boolean required() {
            return false;
        }

        @Override
        public Class<? extends Decoder> decoder() {
            return Decoder.class;
        }

        @Override
        public Class<?> implementation() {
            return Object.class;
        }

        @Override
        public Class<? extends Encoder> encoder() {
            return Encoder.class;
        }

        @Override
        public boolean nullable() {
            return true;
        }

        @Override
        public boolean collectionValueNullable() {
            return true;
        }

        @Override
        public String defaultValueToOmit() {
            return "";
        }

        @Override
        public Class<? extends Annotation> annotationType() {
            return JsonProperty.class;
        }
    };
}
 
Example 15
Source File: ReflectiveTypeAdapterFactory.java    From letv with Apache License 2.0 4 votes vote down vote up
private String getFieldName(Field f) {
    SerializedName serializedName = (SerializedName) f.getAnnotation(SerializedName.class);
    return serializedName == null ? this.fieldNamingPolicy.translateName(f) : serializedName.value();
}
 
Example 16
Source File: SchemaTest.java    From mapbox-events-android with MIT License 4 votes vote down vote up
private void schemaContainsFields(JsonObject schema, List<Field> fields) {
  int distanceRemainingCount = 0;
  int durationRemainingCount = 0;

  for (int i = 0; i < fields.size(); i++) {
    String thisField = String.valueOf(fields.get(i));
    String[] fieldArray = thisField.split(" ");
    String[] typeArray = fieldArray[fieldArray.length - 2].split("\\.");
    String type = typeArray[typeArray.length - 1];

    String[] nameArray = fieldArray[fieldArray.length - 1].split("\\.");
    String field = nameArray[nameArray.length - 1];

    SerializedName serializedName = fields.get(i).getAnnotation(SerializedName.class);

    if (serializedName != null) {
      field = serializedName.value();
    }

    if (field.equalsIgnoreCase("durationRemaining")) {
      durationRemainingCount++;

      if (durationRemainingCount > 1) {
        field = "step" + field;
      }
    }

    if (field.equalsIgnoreCase("distanceRemaining")) {
      distanceRemainingCount++;

      if (distanceRemainingCount > 1) {
        field = "step" + field;
      }
    }

    JsonObject thisSchema = findSchema(schema, field);
    assertNotNull(thisSchema);

    if (thisSchema.has("type")) {
      typesMatch(thisSchema, type);
    }
  }
}
 
Example 17
Source File: ReflectiveTypeAdapterFactory.java    From framework with GNU Affero General Public License v3.0 4 votes vote down vote up
static String getFieldName(FieldNamingStrategy fieldNamingPolicy, Field f) {
  SerializedName serializedName = f.getAnnotation(SerializedName.class);
  return serializedName == null ? fieldNamingPolicy.translateName(f) : serializedName.value();
}