我使用了上面@Toongerges建议的变体。下面是一个实用类,它将“异常安全”转换为JSON。返回的JSON中会有一个额外的元素,名为“exceptionMessages”,其中包含JSON序列化失败的属性(如果不是Java bean属性,则包含方法名)。如果这种风格更适合您,可以更改它以返回一对JsonNode,一个用于对象,另一个用于异常消息
import static java.util.stream.Collectors.toMap;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.apache.commons.lang3.exception.ExceptionUtils;
public abstract class JsonUtils {
private static ObjectMapper mapper = new ObjectMapper();
/**
* This is only useful in the context of converting a object whose methods could throw exceptions
* into JSON. By default a "getName" method that throws an exception will fail the whole
* serialization however with this method such exceptions will be swallowed and there will be a
* "exceptionMessages" element in the returned JSON which contains all failures
*
* To be used only when working with legacy code.
*/
@SuppressWarnings("unchecked")
public static <U> ObjectNode exceptionSafeWrite(Class<U> sourceClazz, U obj, boolean prettyPrint) {
GuardedInvocationHandler handler = new GuardedInvocationHandler(obj);
U proxiedObject = (U) Proxy
.newProxyInstance(sourceClazz.getClassLoader(), new Class<?>[]{sourceClazz}, handler);
ObjectNode originalNode = mapper.convertValue(proxiedObject, ObjectNode.class);
ObjectNode exceptionMessages = mapper.convertValue(handler.getExceptionMessagesForJson(), ObjectNode.class);
originalNode.put("exceptionMessages", exceptionMessages);
return originalNode;
}
private static class GuardedInvocationHandler implements InvocationHandler {
private final Object target;
private Map<Method, Throwable> exceptionMap = new LinkedHashMap<>();
private Map<Method, String> methodToPropertyNameMap;
private GuardedInvocationHandler(Object target) {
this.target = target;
this.methodToPropertyNameMap = methodToPropertyNameMap(target.getClass());
}
private static Map<Method, String> methodToPropertyNameMap(Class<?> clazz) {
try {
return Stream.of(Introspector.getBeanInfo(clazz).getPropertyDescriptors())
.collect(toMap(d -> d.getReadMethod(), d -> d.getName()));
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
exceptionMap.put(method, e.getTargetException());
return null;
} catch (Exception e) {
exceptionMap.put(method, e);
return null;
}
}
public Map<String, String> getExceptionMessagesForJson() {
return exceptionMap.entrySet().stream().collect(
toMap(e -> methodToPropertyNameMap.getOrDefault(e.getKey(), e.getKey().getName()),
e -> ExceptionUtils.getMessage(e.getValue())));
}
}
}