使用gson反序列化反序列化对象的内部对象

Deserialize inner object of deserialized object using gson

我们正在反序列化顶级 RefundAttrs 属性,同时从数据库中获取交易对象。我无法更改这部分。

如何将 RefundAttrs.metadata 字段反序列化为 RefundEventData?我得到 com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 52 path $.reason

    class RefundAttrs {
        private String instrumentTxnId;
        private Object metadata;

        public String instrumentTxnId() {
            return instrumentTxnId;
        }

        public Object metadata() {
            return metadata;
        }

        @Override
        public String toString() {
            return String.format("{ instrumentTxnId=%s, metadata=%s }", this.instrumentTxnId, this.metadata);
        }
    }

    class RefundEventData {
        private String orderId;
        private Double refundAmount;
        private String reason;

        @Override
        public String toString() {
            return String.format("{ orderId=%s, refundAmount=%s, reason=%s }", this.orderId, this.refundAmount, this.reason);
        }
    }

    public static void main(String[] args) throws IOException {
        Gson gson = new Gson();
        String json = "{\n" +
                "  \"instrumentTxnId\": \"refund-101\",\n" +
                "  \"metadata\": {\n" +
                "    \"orderId\": \"011-acf\",\n" +
                "    \"refundAmount\": 100.0,\n" +
                "    \"reason\": \"User left\"\n" +
                "  }\n" +
                "}";
        RefundAttrs attrs = gson.fromJson(json, RefundAttrs.class);

        System.out.println(attrs.metadata());
        // {orderId=011-acf, refundAmount=100.0, reason=User left}
        RefundEventData eventData = gson.fromJson(attrs.metadata().toString(), RefundEventData.class);
}

attrs.metadata().toString() 生成无效的 JSON 文本。

将元数据转换为 JSON:

RefundEventData eventData = gson.fromJson(gson.toJson(attrs.metadata()), RefundEventData.class);