Reputation: 47
We are using Grails version 3.2. I have the json response and Domain object like below. How can we parse json response into domain object using groovy to save in our db without manually converting all the json response elements into my domain properties.
json response
{
"orderId": 1,
"orderDateTime": "07/10/2020",
"orderTypeId": 1,
"userId": "12345",
"StateId": "5"
}
Domain object:
class Order {
Long id
Date orderDate
Long orderType
Long user
Long state
}
Upvotes: 0
Views: 759
Reputation: 527
The JsonSlurper class can do this for you.
The easiest way is like this:
json = new JsonSlurper().parseText( jsonStrIn )
order = new Order( json )
But that only works if:
If that's not the case, as it isn't in the sample you provided, then it's a little more complex.
To work around the name differences you can create a map of JSON names to domain names and use the map to modify the JSON string before you parse it.
Map propertyNameMap = [
'orderId': 'id',
'orderDateTime': 'orderDate',
'orderTypeId': 'orderType',
'userId': 'user',
'StateId': 'state'
]
propertyNameMap.each { jsonName, domainName ->
jsonStrIn = jsonStrIn.replaceAll( jsonName, domainName )
}
You might need to use a regular expression, if the JSON property names can occur in the value strings.
The following code will populate your domain from the JSON, correctly translating from String to long (where needed) and allowing for differences in property names.
import groovy.json.JsonSlurper
import java.text.SimpleDateFormat
String jsonStrIn = '''{
"orderId": 1,
"orderDateTime": "07/10/2020",
"orderTypeId": 1,
"userId": "12345",
"StateId": "5"
}'''
@groovy.transform.ToString
class Order {
Long id
Date orderDate
Long orderType
Long user
Long state
void setOrderDate( String dt ) {
orderDate = new SimpleDateFormat('dd/MM/yyyy').parse( dt )
}
void setUser( String uid ) {
user = Long.parseLong( uid )
}
}
Map propertyNameMap = [
'orderId': 'id',
'orderDateTime': 'orderDate',
'orderTypeId': 'orderType',
'userId': 'user',
'StateId': 'state'
]
propertyNameMap.each { jsonName, domainName ->
jsonStrIn = jsonStrIn.replaceAll( jsonName, domainName )
}
println jsonStrIn
json = new JsonSlurper().parseText( jsonStrIn )
order = new Order( json )
println order
Running the above example will display the translated JSON and the Order instance created from it.
{
"id": 1,
"orderDate": "07/10/2020",
"orderType": 1,
"user": "12345",
"state": "5"
}
Order(1, Wed Oct 07 00:00:00 BST 2020, 1, 12345, 53)
[Done] exited with code=0 in 1.677 seconds```
Upvotes: 1