-
Notifications
You must be signed in to change notification settings - Fork 8.1k
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
Is there a to set a custom JSON serializer/deserializer? #4112
Comments
Hey I was wondering the same exact thing since I was trying to serialize all my In the meantime though, gin has a 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 // this code is a copy-paste of the existing render.JSON struct except for the json package being used for marshalling
import (
"net/http"
"github.com/gin-gonic/gin/render"
"github.com/go-json-experiment/json/v1"
)
type JSONv2 struct {
render.JSON
}
func (r JSONv2) Render(w http.ResponseWriter) error {
writeContentType(w, []string{"application/json; charset=utf-8"})
jsonBytes, err := json.Marshal(r.Data)
if err != nil {
return err
}
_, err = w.Write(jsonBytes)
return err
}
func writeContentType(w http.ResponseWriter, value []string) {
header := w.Header()
if val := 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:
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 |
Thank you |
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: