컨트롤러에서 JSON에 배열을 추출하는 방법을 잘 모르겠습니다. 제품 배열이있는 주문이 포함 된 JSON 개체가 있습니다. JSON은 이런 식으로 중첩되어 있지만 간결하게하기 위해 나는 많은 필드를 줄였습니다.내장 배열이있는 JSON 객체 컨트롤러에 저장
{ "customerId": "23", "customerName": "Johnson",
"products":[
{
"productId": "1",
"finalPrice": "1.00"
},
{
"productId": "2",
"finalPrice": "2.00"
},
{
"productId": "3",
"finalPrice": "3.00"
}
]}
나는 다음이 걸릴를 분석하고 두 테이블 ... 주문 및 OrdersProducts에 저장해야하는 컨트롤러 코드가 있습니다. 이것은 지금까지 내가 가지고있는 것입니다. 그러나 그것의 올바르지 않은 것들은 어떻게 input과 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)
// ???????
}
}
---------- (에서 아래의 답을 복용하고 내 특정 필요에 맞게 수정 한 후 MY 솔루션 ----------
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 }
}
}
}
불행하게도 자사의 레거시 데이터베이스와 두 개의 필드를 통해 연결 할 수 있습니다. 그래서 저는 이것을 수동으로해야합니다. Orders '클래스에 – JPM
을 추가하면'hasMany '를 사용하여'OrdersProduct '와 연결할 수 있습니다. 이것이 가능하지 않다면, j.products.each {new OrderProducts (it)} – aldrin
루프를 통해 루프를 반복 할 수 있습니다. grails.converters.JSON.parse 오류도 "No signature of method : 정적 grails.converters.JSON.parse()는 인수 유형에 적용 가능합니다. (org.codehaus.groovy.grails.web.json.JSONObject "Grails를 사용하는 이유는 무엇인가 간단하고 결코 단순하지 않습니다.) – JPM