
com.paypal.http.serializer.ObjectMapper Maven / Gradle / Ivy
package com.paypal.http.serializer;
import com.paypal.http.annotations.Model;
import com.paypal.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 || value == 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
© 2015 - 2025 Weber Informatics LLC | Privacy Policy