2013-05-15 3 views
1

같은 클래스의 특정 속성을 보내 :어떻게에만 이와 같은 내가 간단한 동작을 JSON

def showSomething() { 
    render Color.get(params.id) as JSON 
} 

이 JSON로 Color 클래스의 모든 속성을 렌더링합니다. 그러나 두 속성 (예 : colorName and shade) 만 렌더링하려는 경우 어떻게해야합니까?

def relevantProperties = ["colorName","shade"] 
def color = Color.get(params.id) 
def reply = relevantProperties.collectEntries { property -> 
    [property, color[property]] 
} 

render reply as JSON 

거기 당신은 내가 사용 Grails는,

누군가가 저를 수정할 수} :-)

답변

2

Gjordis는 개체를 렌더링 할 때마다 동일한 속성을 렌더링하려는 경우 올바른 옵션을 제공합니다. 그러나 간단히 이렇게 할 수 있습니다 :

Color color = Color.get(params.id) 
render ([colorName: color.colorName, shade: color.shade] as JSON) 
2

이것은 매우 간단하다. 그러나 변환에서 호출 된 함수를 재정의하는 것이 핵심입니다.

1
import grails.converters.JSON 
class BootStrap { 
    def init = {servletContext -> 
     JSON.registerObjectMarshaller(Color) { 
      def returnArray = [:] 
      returnArray['shade'] = it.shade 
      returnArray['colorName'] = it.colorName 
      return returnArray 
    } 

하지 않은 있습니다

+0

이것은 약간의 융통성이 부족하지 않습니까? – fabiangebert

+0

변환기를 클래스에 등록합니다. 당신은 한번만 할 필요가 있습니다. JSON으로 render ...를 호출 할 때마다 같은 값을 반환합니다. – Gjordis

관련 문제