com.braintreepayments.http.serializer.ObjectMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of braintreehttp Show documentation
Show all versions of braintreehttp Show documentation
This is Braintree's generic http library for generated SDKs
package com.braintreepayments.http.serializer;
import com.braintreepayments.http.annotations.Model;
import com.braintreepayments.http.annotations.SerializedName;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.*;
public class ObjectMapper {
public static Map map(Object o) throws IllegalAccessException {
Map serialized = new HashMap<>();
Class oClass = o.getClass();
for (Field f : oClass.getDeclaredFields()) {
if (!Modifier.isTransient(f.getModifiers())) {
f.setAccessible(true);
SerializedName sn = f.getAnnotation(SerializedName.class);
if (sn == null) {
continue;
}
String key = sn.value();
Object value = f.get(o);
if (value != null) {
if (isPrimitive(value)) {
serialized.put(key, value);
} else if (value instanceof List) {
List valueList = new ArrayList();
for (Object subValue : (List) value) {
if (isPrimitive(subValue)) {
valueList.add(subValue);
} else {
valueList.add(map(subValue));
}
}
serialized.put(key, valueList);
} else {
serialized.put(key, map(value));
}
}
}
}
return serialized;
}
@SuppressWarnings("unchecked")
public static T unmap(Map inputData, Class cls) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
T instance = cls.getConstructor().newInstance();
for (String key : inputData.keySet()) {
Object value = inputData.get(key);
Field f = fieldForSerializedName(key, cls);
if (f == null) {
continue;
}
SerializedName sn = f.getAnnotation(SerializedName.class);
f.setAccessible(true);
if (isPrimitive(value)) {
if (isNumeric(f.getType())) {
f.set(instance, numericCast(f.getType(), (Number) value));
} else {
f.set(instance, value);
}
} else if (value instanceof List) {
Class listClass = sn.listClass();
if (listClass.equals(Void.class)) {
throw new InstantiationException("Generated array properties must set the listClass property on SerializedName");
}
List destList = new ArrayList();
if (isPrimitive(listClass)) {
List sourceList = (List) value;
for (Object sourceListValue : sourceList) {
destList.add(listClass.cast(sourceListValue));
}
} else {
List