Not sure how to extract the array in JSON from controller. I have a JSON Object that contains an order with an array of products. The JSON is nested like this but for brevity I reduced the many fields I have.
{ "customerId": "23", "customerName": "Johnson",
"products":[
{
"productId": "1",
"finalPrice": "1.00"
},
{
"productId": "2",
"finalPrice": "2.00"
},
{
"productId": "3",
"finalPrice": "3.00"
}
]}
I then have a Controller code that needs to take this and parse it and save it into two tables… Orders and OrdersProducts. This is what I have so far but its not right some how have to take input and for loop each item and save.
class OrdersController {
def save = {
def input = request.JSON
def order = new Orders(input)
order.save(flush:true)
// Somehow I have to loop this for each item in array???
def products = new OrdersProducts(input)
products.ordersId = order.id
products.save(flush:true)
// ???????
}
}
———- MY SOLUTION ———-
After taking answer from below and modifying it to suit my particular needs,(legacy database structure), this is what I did to manually insert each product:
OrdersController.groovy
import grails.converters.JSON
import grails.converters.XML
class OrdersController {
def save = {
def i
def input = request.JSON
def order = new Orders(input)
if (order.save(failOnError:true)) {
for (def products: input.ordersProducts) {
def prod = new OrdersProducts(products)
prod.ordersId = order.id
if (prod.save(failOnError:true)) {
//
} else {
prod.errors.allErrors.each { println it }
}
}
} else {
order.errors.each { println it }
}
}
}
Are ‘Orders’ and ‘OrdersProducts’ related? I’m guessing they are related as,
In this case, you can parse the string to JSON and then initialize the objects,