我通常使用json编码库。看看下面的例子:
package main
import (
"encoding/json"
"time"
)
type myJSON struct {
IntValue int `json:"intValue"`
BoolValue bool `json:"boolValue"`
StringValue string `json:"stringValue"`
DateValue time.Time `json:"dateValue"`
ObjectValue *myObject `json:"objectValue"`
NullStringValue *string `json:"nullStringValue"`
NullIntValue *int `json:"nullIntValue"`
}
type myObject struct {
ArrayValue []int `json:"arrayValue"`
}
func main() {
otherInt := 4321
data := &myJSON{
IntValue: 1234,
BoolValue: true,
StringValue: "hello!",
DateValue: time.Date(2022, 3, 2, 9, 10, 0, 0, time.UTC),
ObjectValue: &myObject{
ArrayValue: []int{1, 2, 3, 4},
},
NullStringValue: nil,
NullIntValue: &otherInt,
}
bytes, err := json.Marshal(data) // <-------------------This line
println(string(bytes)) // <-------------------And this line
println(err)
}
输出:
{"intValue":1234,"boolValue":true,"stringValue":"hello!","dateValue":"2022-03-02T09:10:00Z","objectValue":{"arrayValue":[1,2,3,4]},"nullStringValue":null,"nullIntValue":4321}