使用 gson 反序列化反序列化对象的内部对象
Posted
技术标签:
【中文标题】使用 gson 反序列化反序列化对象的内部对象【英文标题】:Deserialize inner object of deserialized object using gson 【发布时间】:2021-12-08 04:25:48 【问题描述】:我们在从数据库获取交易对象时反序列化*** 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);
【问题讨论】:
【参考方案1】:attrs.metadata().toString()
生成无效的 JSON 文本。
将元数据转换为 JSON:
RefundEventData eventData = gson.fromJson(gson.toJson(attrs.metadata()), RefundEventData.class);
【讨论】:
以上是关于使用 gson 反序列化反序列化对象的内部对象的主要内容,如果未能解决你的问题,请参考以下文章