将 JSON 数组转换为对象数组 - Apache 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"
}
]
如何使用 'groovy script/java'
拆分从此 json 创建对象数组
如果 StartDate 为 null,[Name, ID, ValueAction, ValueSource] 这里 ValueAction/ValueSource 应该为 null。所以数组应该是这样的。
[[ABC,1, , lmn],[PQR,2, , ],[XYZ,3, , ]]
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]]'
下次请 post 有效 JSON.
[
{
"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"
}
]
如何使用 'groovy script/java'
拆分从此 json 创建对象数组 如果 StartDate 为 null,[Name, ID, ValueAction, ValueSource] 这里 ValueAction/ValueSource 应该为 null。所以数组应该是这样的。
[[ABC,1, , lmn],[PQR,2, , ],[XYZ,3, , ]]
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]]'
下次请 post 有效 JSON.