GSON 无法使用 Java 17 序列化异常

问题描述 投票:0回答:3

以下代码用于 Java 11:

new Gson().toJson(new Exception())

在 JDK 17 上我得到以下错误:

Unable to make field private java.lang.String java.lang.Throwable.detailMessage accessible: module java.base does not "opens java.lang" to unnamed module @147ed70f

从阅读this page,我想我可以用

--add-opens java.base/java.lang=ALL-UNNAMED
解决它。但是有更好的方法吗?也许使用自定义反序列化器?

java gson
3个回答
1
投票

我昨天有这个。我当时使用的是 Java 17。我回到了 Java 11,它运行良好。

我觉得是因为这个:https://bugs.openjdk.java.net/browse/JDK-8256358

我比较懒,用的是GSON默认的反射型适配器。

你必须实现你自己的 TypeAdapter 来修复它。或者也许使用另一个像 Jackson 这样的 JSON 反序列化器,我稍后可能会这样做。


0
投票

这是我添加的用于反序列化异常的代码。这可以在这样的类中使用:

public class Result {
    public final Object result;
    public final Error error;

    public Result(Object result) { ... }

    public Result(Exception e) {
        this.result = null;
        this.error = new Error(e);
    }
}

另一方面,打电话给

result.error.toThrowable()

public static class Error {
    public final String message;
    public final List<STE> stackTrace;
    public final Error cause;

    public Error(Throwable e) {
        message = e.getMessage();
        stackTrace = Arrays.stream(e.getStackTrace()).map(STE::new).collect(Collectors.toList());
        cause = e.getCause() != null ? new Error(e.getCause()) : null;
    }

    public Throwable toThrowable() {
        Throwable t = new Throwable(message);
        t.setStackTrace(stackTrace.stream().map(STE::toStackTraceElement).toArray(StackTraceElement[]::new));
        if (cause != null) {
            t.initCause(cause.toThrowable());
        }
        return t;
    }

    private static class STE {
        public final String declaringClass;
        public final String methodName;
        public final String fileName;
        public final int    lineNumber;

        public STE(StackTraceElement ste) {
            this.declaringClass = ste.getClassName();
            this.methodName = ste.getMethodName();
            this.fileName = ste.getFileName();
            this.lineNumber = ste.getLineNumber();
        }

        public StackTraceElement toStackTraceElement() {
            return new StackTraceElement(declaringClass, methodName, fileName, lineNumber);
        }
    }
}

-1
投票

尝试使用最新版本。

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

https://mvnrepository.com/artifact/com.google.code.gson/gson

© www.soinside.com 2019 - 2024. All rights reserved.