I am not familiar with usage of golang tags
, I want to change the default action of convertion:
type CvJdRelationInfo struct {
JdId string
CvId string
Status int16
AcceptTimestamp int64
}
json
tag will auto convert:
JdId -> JdId
CvId -> CvId
Status -> Status
AcceptTimestamp -> AcceptTimestamp
bson
tag will auto convert:
JdId -> jdid
CvId -> cvid
Status -> status
AcceptTimestamp -> accepttimestamp
Can I change the default action, such as json
bson
tags will do this:
JdId -> jdId
CvId -> cvId
Status -> status
AcceptTimestamp -> acceptTimeStamp
So I can omission all tags each time(why should I write tags each time if default action is just what I want?)
type CvJdRelationInfo struct {
JdId string `json:"jdId" bson:"jdId"`
CvId string `json:"cvId" bson:"cvId"`
Status int16 `json:"status" bson:"status"`
AcceptTimestamp int64 `json:"acceptTimestamp" bson:"acceptTimestamp"`
}
You can try:
type CvJdRelationInfo struct {
JdId string `bson:"jdId" json:"jdId"`
CvId string `bson:"cvId" json:"cvId"`
Status int16 `bson:"status" json"status"`
AcceptTimestamp int64 `bson:"acceptTimeStamp" json:"acceptTimeStamp"`
}
You can't change the default behavior of the encoding/json
package. It's built into it and there is no exported variable or function which would change it. Nothing to discuss on it.
The object's default key string is the struct field name but can be specified in the struct field's tag value.
One thing to note here is that even though marshaling a value to JSON will use the exported, uppercased name, but when you unmarshal, the json
package is "intelligent" enough to match lowercased names to uppercased field names too.
See this example:
s := struct{ X, Y int }{}
if err := json.Unmarshal([]byte(`{"X":1,"y":2}`), &s); err != nil {
panic(err)
}
fmt.Printf("%+v", s)
It will print (Go Playground):
{X:1 Y:2}
The json
package properly matches the "X"
and "y"
keys to the s.X
and s.Y
fields even though "y"
is written lowercased.