首页 > 解决方案 > 如何使用 Grails 4 JSON 视图呈现域对象的地图

问题描述

这是以下问题的后续:如何将地图呈现为 Grails 4 JSON 视图中的属性

我有以下 JSON 视图,我想mealsByPerson使用_breakfast.gson模板呈现地图的值。另外,我希望能够将allCaps模型属性从传递_foo.gsonbreakfast.gson

/foo/_foo.gson

import rendermapexample.Breakfast

model {
    Float cost
    Date date
    Map<String, Breakfast> mealsByPerson
    Boolean allCaps
}

json {
    date date
    cost cost
    mealsByPerson g.render(mealsByPerson){}  //HOW DO I PASS `allCaps` to this template?

    // This doesn't work  
    // mealsByPerson g.render(mealsByPerson, model: [allCaps: true]){} 
}

/breaskfast/_breaskfast.gson

import rendermapexample.Breakfast

model {
    Breakfast breakfast
    Boolean allCaps
}

json {
    meat allCaps ? breakfast.meat.toUpperCase() : breakfast.meat
    eggs allCaps ? breakfast.eggs.toUpperCase() : breakfast.eggs
    side allCaps ? breakfast.side.toUpperCase() : breakfast.side
}

FooController

package rendermapexample

class FooController {
    static responseFormats = ['json', 'xml']
    
    def index() {
        Map<String, Breakfast> mealsByPerson = [
            Tom: new Breakfast(meat: "bacon", eggs: "scrambled", side: "hashbrowns"),
            Jack: new Breakfast(meat: "sausage", eggs: "over easy", side: "pancakes")
        ]

        render template: "foo", model: [
            cost: 12.34f, 
            date: new Date(), 
            mealsByPerson: mealsByPerson, 
            allCaps: params.boolean("allCaps")
        ]
    }
}

期望的输出

http://localhost:8080/foo

{
    "cost": 12.34,
    "date": "2021-09-25T01:11:39Z",
    "mealsByPerson": {
        "Tom": {
            "eggs": "scrambled",
            "meat": "bacon",
            "side": "hashbrowns"
        },
        "Jack": {
            "eggs": "over easy",
            "meat": "sausage",
            "side": "pancakes"
        }
    }
}

http://localhost:8080/foo?allCaps=true

{
    "cost": 12.34,
    "date": "2021-09-25T01:11:39Z",
    "mealsByPerson": {
        "Tom": {
            "eggs": "SCRAMBLED",
            "meat": "BACON",
            "side": "HASHBROWNS"
        },
        "Jack": {
            "eggs": "OVER EASY",
            "meat": "SAUSAGE",
            "side": "PANCAKES"
        }
    }
}

示例项目

https://github.com/tonyerskine/rendermapexample

标签: jsongrailsgson

解决方案


重新审视问题

我重新审视了这个问题和我之前的答案,并决定发布这个而不是编辑前者,在这里解决收到的一些评论/建议,以改进我提出的解决方案。

我将表示逻辑从域类中移开。为此,我探索了三种不同的方法:

  1. 使用 Grails 服务
  2. 在 JSON 视图端编码
  3. 仅使用模板

只是为了清楚起见,我在中添加了以下映射URLMappings.groovy

   "/approach1"(controller: 'foo', action:'approach1')
   "/approach2"(controller: 'foo', action:'approach2')
   "/approach3"(controller: 'foo', action:'approach3')

方法 1:使用 Grails 服务

请注意,在FooController服务 beanfooService中作为参数包含在respond对 JSON 视图的调用中。

FooService.groovy

package rendermapexample

import grails.gorm.transactions.Transactional

@Transactional
class FooService {

    def toAllCaps(mealsByPerson) {        
        mealsByPerson.each { person, breakfast ->
            def breakfastMap = [:]
            breakfast.properties.each { key, value ->
                if (value && value.class == String) {
                    breakfastMap[key] = value.toUpperCase() 
                } else {
                    breakfastMap[key] = value
                } 
            }
            mealsByPerson[person] = breakfastMap 
        }
        return mealsByPerson
    }

}

FooController.groovy

package rendermapexample

class FooController {
    static responseFormats = ['json', 'xml']

    def fooService

    def approach1() {

        Map<String, Breakfast>  mealsByPerson = [
            Tom: new Breakfast(meat: "bacon", eggs: "scrambled", side: "hashbrowns"),
            Jack: new Breakfast(meat: "sausage", eggs: "over easy", side: "pancakes")
        ]

        respond cost: 12.34f,
                date: new Date(),
                mealsByPerson: mealsByPerson,
                allCaps: params.boolean("allCaps"),
                fooService: fooService
        
    }
}

方法1.gson

import rendermapexample.Breakfast
import rendermapexample.FooService

model {
    Float cost
    Date date
    Map<String, Breakfast> mealsByPerson
    Boolean allCaps
    FooService fooService
}

json {
    date date
    cost cost   
    mealsByPerson g.render(allCaps ? fooService.toAllCaps(mealsByPerson) : mealsByPerson)
}

当然fooService,我们可以不将 bean 作为参数传递,而是将toAllCaps代码放入 POJO 静态实用程序类中,然后将其导入approach2.gson.

方法 2:在 JSON 视图端编码

如果 JSON 视图方面需要更多控制,我们可以将toAllCaps函数从FooService.groovy移至approach1.gson,然后丢弃FooService.groovy

FooController.groovy

package rendermapexample

class FooController {
    static responseFormats = ['json', 'xml']

    def approach2() {

        Map<String, Breakfast>  mealsByPerson = [
            Tom: new Breakfast(meat: "bacon", eggs: "scrambled", side: "hashbrowns"),
            Jack: new Breakfast(meat: "sausage", eggs: "over easy", side: "pancakes")
        ]

        respond cost: 12.34f,
                date: new Date(),
                mealsByPerson: mealsByPerson,
                allCaps: params.boolean("allCaps")
        
    }
}

方法2.gson

import rendermapexample.Breakfast

model {
    Float cost
    Date date
    Map<String, Breakfast> mealsByPerson
    Boolean allCaps
}

json {
    date date
    cost cost   
    mealsByPerson g.render(allCaps ? toAllCaps(mealsByPerson) : mealsByPerson)
}


def toAllCaps(mealsByPerson) {        
    mealsByPerson.each { person, breakfast ->
        def breakfastMap = [:]
        breakfast.properties.each { key, value ->
            if (value && value.class == String) {
                breakfastMap[key] = value.toUpperCase() 
            } else {
                breakfastMap[key] = value
            } 
        }
        mealsByPerson[person] = breakfastMap 
    }
    return mealsByPerson
}

方法 3:仅使用模板

在这里,我打算减少传统的 groovy 编码,而更多地依赖 JSON 视图模板,如官方文档中所述

请注意以下注意事项:

  1. 我正在使用的ArrayList变体,mealsByPerson因为 JSON 视图模板的某些功能需要一个实现Iterator接口的对象。 重要提示:这会生成一个单独的单独对象的 JSON 数组,而不是包含原始问题中描述的所有地图条目的单个 JSON 对象。

  2. 我不得不为 JSON 视图禁用静态编译。这是因为其中的一些 JSON 对象名称mealsByPerson是动态的(即它们不仅是标签,而且是实际数据)。即原始帖子中的“Tom”和“Jack”对象名称。

应用程序.yml

grails:
    views:
        json:
            compileStatic: false

FooController.groovy

package rendermapexample

class FooController {
    static responseFormats = ['json', 'xml']

    def approach3() {
        
        ArrayList mealsByPerson = [
            Tom: new Breakfast(meat: "bacon", eggs: "scrambled", side: "hashbrowns"),
            Jack: new Breakfast(meat: "sausage", eggs: "over easy", side: "pancakes")
        ].collect()

        respond cost: 12.34f,
                date: new Date(),
                mealsByPerson: mealsByPerson,
                allCaps: params.boolean("allCaps")
    }
}

方法3.gson

import rendermapexample.Breakfast

model {
    Float cost
    Date date
    ArrayList mealsByPerson
    Boolean allCaps
}

json {
    date date
    cost cost   
    mealsByPerson tmpl.mealsByPerson(mealsByPerson, [allCaps: allCaps]) 
}

_mealsByPerson.gson

import rendermapexample.Breakfast

model {
    Map.Entry mealsByPerson
    Boolean allCaps
}

String person = mealsByPerson.key
Breakfast breakfast = mealsByPerson.value

json {
    "${person}" tmpl.breakfast(breakfast:breakfast, allCaps:allCaps) 
}

_breakfast.gson

import rendermapexample.Breakfast

model {
    Breakfast breakfast
    Boolean allCaps
}


json {
    if (allCaps) {
        meat breakfast.meat.toUpperCase()
        eggs breakfast.eggs.toUpperCase()
        side breakfast.side.toUpperCase()
    } else {
        meat breakfast.meat
        eggs breakfast.eggs
        side breakfast.side
    }
}


推荐阅读