使用Groovy连接JSON数组/对象

时间:2015-03-04 01:21:23

标签: arrays json groovy concat jsonslurper

如何使用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"
  }
  ]
  }

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

1 个答案:

答案 0 :(得分: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]))