在 Java 中使用 Jackson 反序列化异常/可抛出时出现的问题

2022-09-04 21:11:29

我在使用 Jackson(版本 2.2.1)反序列化和实例时遇到了问题。请考虑以下代码段:ExceptionThrowable

public static void main(String[] args) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);

    try {
        Integer.parseInt("String");
    }
    catch (NumberFormatException e) {
        RuntimeException runtimeException = new RuntimeException(e);
        String serializedException = objectMapper.writeValueAsString(runtimeException);
        System.out.println(serializedException);
        Throwable throwable = objectMapper.readValue(serializedException, Throwable.class);
        throwable.printStackTrace();
    }
}

块中的 输出为:System.out.printlncatch

{
  "@class" : "java.lang.RuntimeException",
  "detailMessage" : "java.lang.NumberFormatException: For input string: \"String\"",
  "cause" : {
    "@class" : "java.lang.NumberFormatException",
    "detailMessage" : "For input string: \"String\"",
    "cause" : null,
    "stackTrace" : [ {
      "declaringClass" : "java.lang.NumberFormatException",
      "methodName" : "forInputString",
      "fileName" : "NumberFormatException.java",
      "lineNumber" : 65
    }, {
      "declaringClass" : "java.lang.Integer",
      "methodName" : "parseInt",
      "fileName" : "Integer.java",
      "lineNumber" : 492
    }, {
      "declaringClass" : "java.lang.Integer",
      "methodName" : "parseInt",
      "fileName" : "Integer.java",
      "lineNumber" : 527
    }, {
      "declaringClass" : "test.jackson.JacksonTest",
      "methodName" : "main",
      "fileName" : "JacksonTest.java",
      "lineNumber" : 26
    } ],
    "suppressedExceptions" : [ "java.util.ArrayList", [ ] ]
  },
  "stackTrace" : [ {
    "declaringClass" : "test.jackson.JacksonTest",
    "methodName" : "main",
    "fileName" : "JacksonTest.java",
    "lineNumber" : 29
  } ],
  "suppressedExceptions" : [ "java.util.ArrayList", [ ] ]
}

这似乎很好。但是当我尝试使用 反序列化它时,我得到以下异常:objectMapper.readValue()

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "declaringClass" (class java.lang.StackTraceElement), not marked as ignorable
 at [Source: java.io.StringReader@3c5ebd39; line: 9, column: 27] (through reference chain: java.lang.StackTraceElement["declaringClass"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
    at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
    at com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StackTraceElementDeserializer.deserialize(JdkDeserializers.java:414)
    at com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StackTraceElementDeserializer.deserialize(JdkDeserializers.java:380)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:151)
...

然后,我尝试使用 mix-in 注释来忽略 in ,但现在反序列化的在其堆栈跟踪中不包含声明类:declaringClassjava.lang.StackTraceElementException

java.lang.RuntimeException: java.lang.NumberFormatException: For input string: "String"
    at .main(JacksonTest.java:33)
Caused by: java.lang.NumberFormatException: For input string: "String"
    at .forInputString(NumberFormatException.java:65)
    at .parseInt(Integer.java:492)
    at .parseInt(Integer.java:527)
    at .main(JacksonTest.java:30)

我错过了什么吗?任何帮助都非常感谢。


答案 1

这里似乎有一个Jackson JIRA条目。Jackson 似乎无法处理 in,因为与此字段对应的 getter 称为 。declaringClassjava.lang.StackTraceElementgetClassName()

我通过使用上面提到的JIRA条目中建议的自定义包装器来解决此问题。自定义包装器 () 将包含字段 、 、 和 以及相应的 getter 和 setter。我将块(在问题中提到)修改为如下所示:StackTraceElementCustomStackTraceElementdeclaringClassmethodNamefileNamelineNumbercatch

catch (NumberFormatException e) {
    RuntimeException runtimeException = new RuntimeException(e);
    e.printStackTrace();
    String serializedException = objectMapper.writeValueAsString(runtimeException);
    System.out.println(serializedException);

    String serializedStackTrace = objectMapper.writeValueAsString(transformStackTrace(runtimeException));
    String serializedStackTraceForCause = objectMapper.writeValueAsString(transformStackTrace(runtimeException.getCause()));

    Throwable throwable = objectMapper.readValue(serializedException, Throwable.class);
    List<CustomStackTraceElement> customStackTraceElementList = objectMapper.readValue(serializedStackTrace, List.class);
    List<CustomStackTraceElement> customStackTraceElementListForCause = objectMapper.readValue(serializedStackTraceForCause, List.class);

    throwable.setStackTrace(reverseTransformStackTrace(customStackTraceElementList));
    throwable.getCause().setStackTrace(reverseTransformStackTrace(customStackTraceElementListForCause));
    throwable.printStackTrace();
}

在序列化过程中,将按以下方法转换为 :StackTraceElement[]List<CustomStackTraceElement>

private static List<CustomStackTraceElement> transformStackTrace(Throwable throwable)
{
    List<CustomStackTraceElement> list = new ArrayList<>();
    for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
        CustomStackTraceElement customStackTraceElement =
            new CustomStackTraceElement(stackTraceElement.getClassName(),
                                        stackTraceElement.getMethodName(),
                                        stackTraceElement.getFileName(),
                                        stackTraceElement.getLineNumber());

        list.add(customStackTraceElement);
    }

    return list;
}

...并且反向转换将在反序列化期间完成:

private static StackTraceElement[] reverseTransformStackTrace(List<CustomStackTraceElement> customStackTraceElementList)
{
    StackTraceElement[] stackTraceElementArray = new StackTraceElement[customStackTraceElementList.size()];
    for (int i = 0; i < customStackTraceElementList.size(); i++) {
        CustomStackTraceElement customStackTraceElement = customStackTraceElementList.get(i);
        StackTraceElement stackTraceElement =
            new StackTraceElement(customStackTraceElement.getDeclaringClass(),
                                  customStackTraceElement.getMethodName(),
                                  customStackTraceElement.getFileName(),
                                  customStackTraceElement.getLineNumber());

        stackTraceElementArray[i] = stackTraceElement;
    }

    return stackTraceElementArray;
}

现在,在反序列化之后,对象中具有预期的堆栈跟踪。Throwable


答案 2

添加以下内容:

objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

并以与第一次相同的方式消除反序列化异常:

System.out.println( objectMapper.writeValueAsString( throwable ) );

我使用了以下代码:

public static void main( String[] args ) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure( SerializationFeature.INDENT_OUTPUT, true );
    objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setVisibility( PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY );
    objectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY );

    try
    {
        Integer.parseInt( "String" );
    }
    catch( NumberFormatException e )
    {
        Throwable throwable = objectMapper.readValue( objectMapper.writeValueAsString( e ), Throwable.class );
        System.out.println( objectMapper.writeValueAsString( throwable ) );
    }
}

添加了这个jars:jackson-annotations-2.2.0.jar,jackson-core-2.2.0.jar和jackson-databind-2.2.0.jar。

执行后,将打印以下内容:

{
"@class" : "java.lang.NumberFormatException",
"detailMessage" : "For input string: \"String\"",
"cause" : null,
"stackTrace" : [ {
    "declaringClass" : "java.lang.NumberFormatException",
    "methodName" : "forInputString",
    "fileName" : "NumberFormatException.java",
    "lineNumber" : 48,
    "className" : "java.lang.NumberFormatException",
    "nativeMethod" : false
}, {
    "declaringClass" : "java.lang.Integer",
    "methodName" : "parseInt",
    "fileName" : "Integer.java",
    "lineNumber" : 449,
    "className" : "java.lang.Integer",
    "nativeMethod" : false
}, {
    "declaringClass" : "java.lang.Integer",
    "methodName" : "parseInt",
    "fileName" : "Integer.java",
    "lineNumber" : 499,
    "className" : "java.lang.Integer",
    "nativeMethod" : false
}, {
    "declaringClass" : "com.sample.bla.Main",
    "methodName" : "main",
    "fileName" : "Main.java",
    "lineNumber" : 24,
    "className" : "com.sample.bla.Main",
    "nativeMethod" : false
}, {
    "declaringClass" : "sun.reflect.NativeMethodAccessorImpl",
    "methodName" : "invoke0",
    "fileName" : "NativeMethodAccessorImpl.java",
    "lineNumber" : -2,
    "className" : "sun.reflect.NativeMethodAccessorImpl",
    "nativeMethod" : true
}, {
    "declaringClass" : "sun.reflect.NativeMethodAccessorImpl",
    "methodName" : "invoke",
    "fileName" : "NativeMethodAccessorImpl.java",
    "lineNumber" : 39,
    "className" : "sun.reflect.NativeMethodAccessorImpl",
    "nativeMethod" : false
}, {
    "declaringClass" : "sun.reflect.DelegatingMethodAccessorImpl",
    "methodName" : "invoke",
    "fileName" : "DelegatingMethodAccessorImpl.java",
    "lineNumber" : 25,
    "className" : "sun.reflect.DelegatingMethodAccessorImpl",
    "nativeMethod" : false
}, {
    "declaringClass" : "java.lang.reflect.Method",
    "methodName" : "invoke",
    "fileName" : "Method.java",
    "lineNumber" : 597,
    "className" : "java.lang.reflect.Method",
    "nativeMethod" : false
}, {
    "declaringClass" : "com.intellij.rt.execution.application.AppMain",
    "methodName" : "main",
    "fileName" : "AppMain.java",
    "lineNumber" : 120,
    "className" : "com.intellij.rt.execution.application.AppMain",
    "nativeMethod" : false
    } ],
    "message" : "For input string: \"String\"",
    "localizedMessage" : "For input string: \"String\""
}

推荐