1

如何使用 Java 或 Groovy 合并或连接两个独立的不同 JSON 数组或 JSON 对象并将其视为单个 JSON 对象。

请参阅下面的示例 JSON 独立对象我有第一个持有职责信息

[
  {
    "code": "A0001",
    "description": "Do strategic planning for long range goals of the university"
  },
  {
    "code": "A0002",
    "description": "Administer budgets in excess of 1,000,000"
  }]

第二个 JSON 对象包含证书信息

 [
  {
    "code": "CPA",
    "description": "Certified Public Accountant"
  },
  {
    "code": "CPR",
    "description": "Cardiopulmonary Resuscitation"
  },
  {
    "code": "ELE",
    "description": "Electrician's License"
  }]

我需要连接并访问以下格式的两个 JSON `

{
  "duties":
  [{
    "code": "A0001",
    "description": "Do strategic planning for long range goals of the university"
  },
  {
    "code": "A0002",
    "description": "Administer budgets in excess of 1,000,000"
  }],
  "Certificates":
  [
  {
    "code": "CPA",
    "description": "Certified Public Accountant"
  },
  {
    "code": "CPR",
    "description": "Cardiopulmonary Resuscitation"
  },
  {
    "code": "ELE",
    "description": "Electrician's License"
  }
  ]
  }

请让我知道完成此操作的可用选项。谢谢

4

1 回答 1

2

例如,可以通过以下方式完成:

import groovy.json.*

def json1 = """[
  {
    "code": "A0001",
    "description": "Do strategic planning for long range goals of the university"
  },
  {
    "code": "A0002",
    "description": "Administer budgets in excess of 1,000,000"
  }]"""

 def json2 = """[
  {
    "code": "CPA",
    "description": "Certified Public Accountant"
  },
  {
    "code": "CPR",
    "description": "Cardiopulmonary Resuscitation"
  },
  {
    "code": "ELE",
    "description": "Electrician's License"
  }]"""

  def duties = new JsonSlurper().parseText(json1)
  def certs = new JsonSlurper().parseText(json2)  

  println JsonOutput.prettyPrint(JsonOutput.toJson ([duties: duties, certificates: certs]))
于 2015-03-04T05:44:43.790 回答