We are deserializing top-level RefundAttrs attribute while fetching transaction object from DB. I cannot change this part.
How can I deserialize RefundAttrs.metadata field into RefundEventData? I am getting 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);
}
CodePudding user response:
attrs.metadata().toString()
generates invalid JSON text.
Convert the metadata to JSON:
RefundEventData eventData = gson.fromJson(gson.toJson(attrs.metadata()), RefundEventData.class);