2014-10-24 4 views
1

내 코드에이 구조체가 있습니다.이동 중에 json에서 필드를 제거하는 방법은 무엇입니까?

type AppVersion struct { 
    Id   int64  `json:"id"` 
    App   App  `json:"app,omitempty" out:"false"` 
    AppId   int64  `sql:"not null" json:"app_id"` 
    Version  string `sql:"not null" json:"version"` 
    Sessions  []Session `json:"-"` 
    SessionsCount int  `sql:"-"` 
    CreatedAt  time.Time `json:"created_at"` 
    UpdatedAt  time.Time `json:"updated_at"` 
    DeletedAt  time.Time `json:"deleted_at"` 
} 

나는 webservice를 구축 중이므로 App 필드를 JSON에 보낼 필요가 없습니다. JSON에서 필드를 제거하기 위해 몇 가지 시도를했지만 그 작업을 수행 할 수 없었습니다.

어떻게하면됩니까? 구조체를 비어있는 것으로 설정하는 방법이 있습니까?

데이터베이스 액세스 레이어로 GORM을 사용하고 있으므로 App *App을 수행 할 수 있는지 확실하지 않습니다. 작동 여부를 알고 계십니까?

+3

당신이 그것을 시도? 나는 그것이 작동 할 것으로 생각한다. – JimB

+0

시도했지만 작동하지 않습니다. 데이터베이스 생성/마이그레이션에 문제가 있습니다. – ventayol

+0

음, GORM과 같은 문제입니다. 'json' 패키지의 스펙 밖에서 직렬화를 추가로 제어하려면'AppVersion'에 자신의'json.Marshaler'와'json.Unmarshaler'를 구현할 수 있습니다. – JimB

답변

1

당신은 응용 프로그램 필드를 숨 깁니다 사용자 정의 타입으로 데이터 구조를 포장 할 수 있어야한다 :이 노출되는 것을 App 필드를 숨겨야합니다

type ExportAppVersion struct { 
    AppVersion 
    App `json:"-"` 
} 

.

+0

json을 설정하는 데 문제가 있습니다. "-"는 json을 디코딩 할 때 필드를 놓치게됩니다. – ventayol

+0

또한 보내고 싶을 때 제어 할 수있는 옵션이 있습니다. – ventayol

+0

역 직렬화/보내기를 원하면이 구조체에 포장하지 마십시오. – ZeissS

2
type AppVersion struct { 
    Id   int64  `json:"id"` 
    App   App  `json:"-"` 
    AppId   int64  `sql:"not null" json:"app_id"` 
    Version  string `sql:"not null" json:"version"` 
    Sessions  []Session `json:"-"` 
    SessionsCount int  `sql:"-"` 
    CreatedAt  time.Time `json:"created_at"` 
    UpdatedAt  time.Time `json:"updated_at"` 
    DeletedAt  time.Time `json:"deleted_at"` 
} 

더 많은 정보 - json-go

관련 문제