We know that through tags, we can conditionally customize the way of Go JSON serialization, such as json:",omitempty".
We know that through tags, we can conditionally customize the way of Go JSON serialization, such as json:",omitempty". When the value of the field is empty, we can not include this value in the serialized data. And json: “-” can be directly not serialized by JSON, if you want to be serialized key-, you can set the tag to json: “-,” and add a comma.If you implement MarshalJSON() ([]byte, error) and UnmarshalJSON(b []byte) error methods for the type, then this type will use your customized method during serialization and deserialization.
These are our commonly used setting techniques.
If you want to add a field to a struct temporarily, you can create a type temporarily and implement it by embedding the original type. He is not the same as the technique introduced in the article JSON and struct composition in Go. In the article JSON and struct composition in Go, a new type is created by embedding. You need to use this new type when serializing and deserializing. The method in this translation is to painlessly change the MarshalJSON method of the original type. Using Alias to avoid recursive analysis is indeed a very clever way.
The following is the original text:
Go’s encoding/json package makes it really easy to marshal structs to JSON data.
package main
import (
"encoding/json"
"os"
"time"
)
type MyUser struct {
ID int64 `json:"id"`
Name string `json:"name"`
LastSeen time.Time `json:"lastSeen"`
}
func main() {
_ = json.NewEncoder(os