简体   繁体   中英

How to parse json data elements into domain object using groovy

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
}

Use JsonSlurper

The JsonSlurper class can do this for you.

Simple example

The easiest way is like this:

json = new JsonSlurper().parseText( jsonStrIn )
order = new Order( json )

But that only works if:

  • Domain class property names match the JSON property names
  • Every domain property is either a String or has a setter that takes a String argument.

If that's not the case, as it isn't in the sample you provided, then it's a little more complex.

Mapping JSON properties to domain properties

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.

Worked example

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

Code output

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```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM