8

结构不固定的 json 值要怎么反序列化成对象比较好?

 3 years ago
source link: https://www.v2ex.com/t/799259
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Java

结构不固定的 json 值要怎么反序列化成对象比较好?

  x97bgt · 4 小时 15 分钟前 · 979 次点击

json 里面有互斥的字段,要怎么序列化成对象?

比如下面的例子里,要么只有refund字段,要么只有purchase,而且两个字段里的结构是不一样的。

{
    "id": "1234567890",
    "amount": 100,
    "refund": {
        "date": "2021-04-23T18:25:43.511Z",
        "confirmed": true,
        "refund_id": 1234456
    }
}

{
    "id": "1234567890",
    "amount": 100,
    "purchase": {
        "date": "2021-04-23T18:25:43.511Z",
        "purchase_id": 789621
    }
}

现在到的最粗暴的办法,是把每个字段都塞进对象。但这太难看了,而且容易造成混乱。

这种结构下,要怎么设计对象的结构比较好?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK