不知道如何从 Controller 中提取JSON中的数组。我有一个JSON对象,其中包含带有一系列产品的订单。 JSON像这样嵌套,但为简洁起见,我减少了许多字段。
{ "customerId": "23", "customerName": "Johnson",
"products":[
{
"productId": "1",
"finalPrice": "1.00"
},
{
"productId": "2",
"finalPrice": "2.00"
},
{
"productId": "3",
"finalPrice": "3.00"
}
]}
然后,我有一个 Controller 代码,需要使用它并对其进行解析并将其保存到两个表中:Orders和OrdersProducts。到目前为止,这是我所拥有的,但是对于一些必须如何输入并for循环每个项目并保存的问题,这是不正确的。
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)
// ???????
}
}
----------我的解决方案----------
从下面获取答案并对其进行修改以适合我的特殊需求(旧版数据库结构)后,这就是我手动插入每个产品的步骤:
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 }
}
}
}
最佳答案
“订单”和“OrdersProducts”是否相关?我猜他们是相关的,
static hasMany = [ordersProducts: OrderProducts]
在这种情况下,您可以将字符串解析为JSON,然后初始化对象,
...
def j = grails.converters.JSON.parse(input)
def order = new Orders(j)
...
order.ordersProducts = j.products
关于arrays - 具有嵌入式数组的JSON对象保存在Controller中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9756266/