Search code examples
javaarraysjsongroovyapache-camel

Convert JSON array to Object Array - Apache camel


[
  {
    "Name": "ABC", 
    "ID": 1,
    "StartDate": 1444845395112,
    "EndDate": null,
    "ValueAction": null,
    "ValueSource": "lmn"
  }, 
  {
    "Name": "PQR", 
    "ID": 2,
    "StartDate": 1444845395119,
    "EndDate": 1446845395119,
    "ValueAction": null,
    "ValueSource": null
  }, 
  {
    "Name": "XYZ", 
    "ID": 3,
    "StartDate": null,
    "EndDate": null,
    "ValueAction": "qwe",
    "ValueSource": "lmn"
  }
]

How to create object array from this json using split with 'groovy script/java'

[Name, ID, ValueAction, ValueSource] here ValueAction/ValueSource should be null if StartDate is null. So array should be like this.

 [[ABC,1, , lmn],[PQR,2, , ],[XYZ,3, , ]]

Solution

  • import groovy.json.*
    
    def json = new JsonSlurper().parseText '''[
      {
        "Name": "ABC",
        "ID": 1,
        "StartDate": 1444845395112,
        "EndDate": null,
        "ValueAction": null,
        "ValueSource": "lmn"
      },
      {
        "Name": "PQR",
        "ID": 2,
        "StartDate": 1444845395119,
        "EndDate": 1446845395119,
        "ValueAction": null,
        "ValueSource": null
      },
      {
        "Name": "XYZ",
        "ID": 3,
        "StartDate": null,
        "EndDate": null,
        "ValueAction": "qwe",
        "ValueSource": "lmn"
      }
    ]
    '''
    
    def res = json.findResults{ it.StartDate ? [ it.Name, it.ID, it.ValueAction ?: '', it.ValueSource ] : null }
    
    assert res.toString() == '[[ABC, 1, , lmn], [PQR, 2, , null]]'
    

    Next time please post the valid JSON.