You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes, I need to communicate with other services, especially legacy ones.
I require all keys in the JSON response to be formatted in snake_case, lower case, or upper case.
Is there a way to achieve this?
e.g.
Hey I was wondering the same exact thing since I was trying to serialize all my time.Time fields as unix millisecond integers rather than string dates. There is an open PR #3391 which would enable us to fully customize the Marshal/Unmarshal methods that gin uses for json conversion. It might get merged and released for gin v1.11, but that's not definitive.
In the meantime though, gin has a render.Render interface that you can manipulate to serialize the json any way you like.
First, define your custom render function. In my case, I wanted to use the new experimental json/v2 package for marshalling so I could take advantage of their new json options like omitzero and format:unixmilli:
// this code is a copy-paste of the existing render.JSON struct except for the json package being used for marshallingimport (
"net/http""github.com/gin-gonic/gin/render""github.com/go-json-experiment/json/v1"
)
typeJSONv2struct {
render.JSON
}
func (rJSONv2) Render(w http.ResponseWriter) error {
writeContentType(w, []string{"application/json; charset=utf-8"})
jsonBytes, err:=json.Marshal(r.Data)
iferr!=nil {
returnerr
}
_, err=w.Write(jsonBytes)
returnerr
}
funcwriteContentType(w http.ResponseWriter, value []string) {
header:=w.Header()
ifval:=header["Content-Type"]; len(val) ==0 {
header["Content-Type"] =value
}
}
I also added a utility method to make the JSONv2 struct easier to use in my gin endpoints:
Then in your gin code, you just need to invoke the function like so:
c.Render(200, WithJSONv2(res))
And that's it!
Note that this is not as elegant as the open PR since you will need to invoke WithJSONv2 in every endpoint where you want to use your custom serializer. But hopefully whenever the PR gets merged, you can run a quick regex replace on your codebase to convert all these usages back to the normal c.JSON(200, res) that's standard.
Is there a way to set a custom JSON serializer?
Sometimes, I need to communicate with other services, especially legacy ones.
I require all keys in the JSON response to be formatted in snake_case, lower case, or upper case.
Is there a way to achieve this?
e.g.
The text was updated successfully, but these errors were encountered: