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

sbdsn5lh  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(222)

在从数据库提取事务对象时,我们正在反序列化顶级RefundAttrs属性。我无法更改此部分。
我怎么能反序列化退款属性。元数据字段到退款事件数据?我得到的com.google.gson.stream.第1行第52列路径$.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);
}
bqujaahr

bqujaahr1#

attrs.metadata().toString()生成无效的JSON文本。
将元数据转换为JSON:

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

相关问题