New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
encoding/json: add tag to support one-way operation for marshal/unmarshal #26636
Comments
how do we keep the original '-' meanings? |
This is a substantial change to the json package and should be a proposal: https://github.com/golang/proposal Having said that, a couple of ways to do this without adding features come to mind:
|
Most of the changes that would make the language more complex are to avoid some degree of code verbosity, so that's not a point that stands on its own. The advantages of this proposal must outweigh the disadvantages. To do that, this issue should be a proposal, like I suggested above. |
Alternative syntax choicesAnother syntax to achieve this, could be to introduce two new struct-tag prefixes, e.g. type User struct {
Name string `json:"name"`
Password string `jsonMarshal:"password" jsonUnmarshal:"-"``
} This even allows using different values for encode a decode, when desirable. Yet another alternative, would be to allow type User struct {
Name string `json:"name"`
Password string `json:"password,nounmarshal"`
} This is less flexible then multiple struct tags, but faster and easier to write, and more in line with current struct-tags like Use-caseWith either method, this would be even more useful when using embedded structs as a mechanism for including fields into models on the client side of an API where the server has defined read-only fields. In particular so, because custom marshal / unmarshal methods for structs used as embedded fields, does not have the desired effect. Example: package modelprofile
type Model struct {
ID string `json:"id,nomarshal"`
ETag string `json:"_etag,nomarshal"`
}
type WriteInfo struct {
CreatedBy string `json:"createdBy,nomarshal"`
UpdatedBy string `json:"updatedBy,nomarshal"`
CreatedAt *time.Time `json:"createdAt,nomarshal"`
UpdatedAt *time.Time `json:"updatedAt,nomarshal"`
} type User struct {
modelprofile.Model
modelprofile.WriteInfo
Name string `json:"name"`
Password string `json:"password,nounmarshal"`
} |
What did you do?
Now if the field tag is "-", the field is always omitted. sometime, we need one-way operation for marshal/unmarshal.
What did you expect to see?
add
<-
for unmarshal, omit marshal; add->
for marshal, omit unmarshal.tag "<-"
output:
tag "->"
output:
The text was updated successfully, but these errors were encountered: