1

I've this struct in my code.

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"`
}

I'm building a webservice and I don't need to send the App field in the JSON. I've tried a few things to remove the field from the JSON but I haven't been able to do it.

How can I achieve this? Is there any way to set struct as empty?

I'm using GORM as database access layer, so I'm not sure if I can do App *App, do you know if it will work?

5
  • 3
    Have you tried it? I suspect it will work. Commented Oct 24, 2014 at 13:31
  • I've tried and it doesn't work, there's a problem with database creation / migration Commented Oct 24, 2014 at 15:58
  • Well, that sounds like a problem with GORM. You could implement your own json.Marshaler and json.Unmarshaler on AppVersion if you want to further control serialization outside of the spec of the json package. Commented Oct 24, 2014 at 16:15
  • I'm quite new to go, how can I create my custom Marshaler? Commented Oct 24, 2014 at 16:25
  • you implement MarshalJSON and UnmarshalJSON on AppVersion. The json package will call those methods if they exists instead of using its own reflection based marshaling. Commented Oct 24, 2014 at 16:38

2 Answers 2

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"`
}

More info - json-go

Sign up to request clarification or add additional context in comments.

Comments

1

You should be able to wrap your data structure into a custom type which hides the app field:

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

This should hide the App field from being exposed.

3 Comments

The problem os setting the json:"-" is that then I miss the field when decoding the json.
Also I would like to have the option to control when I want to send it back or not.
Don't wrap it in this struct if you want to deserialize / send it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.