7

请问, Java 中如何处理结构和字段不固定的 JSON?

 3 years ago
source link: https://www.v2ex.com/t/798204
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

请问, Java 中如何处理结构和字段不固定的 JSON?

  nanmu42 · 7 小时 22 分钟前 · 479 次点击

在一个 Java 编写的 Flink 任务中,我需要将形如

{
  "type": "A", # 固定字段
  "time": 86400, # 固定字段
  "data": { # 这里的字段和各个字段对应的数据类型都不固定
    "a": 1,
    "b": 2,
    "x": 3
  }
}

这样的 JSON 转化为形如

{
  "work": "A", # 固定字段,对应上面的 type
  "duration": 86400, # 固定字段
  "payload": { # 对应上一个 JSON 的 data 部分
    "a_name": 1, # 字段名会被映射转换,部分字段会被丢掉
    "x_name": 3,
    "what": "ever" # 会有新增字段
  }
}

的 JSON,请问:

  1. 这个需求如何解决比较方便呢?
  2. 我可以为两种 JSON 定义 POJO 吗(我还有访问其中固定字段和判断处理的需求,这样是不是方便些?)?如何处理其中结构和字段不固定的部分呢?(定义成某种 Map 类型?我没有多少 Java 的经验)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK