我想你没有提到你的错误,但下面的内容对我很有效.你可以这样试一试.
package main
import (
"encoding/json"
"fmt"
)
type Tweet struct {
UserId int `json:"user_id"`
Message string `json:"message"`
}
func main() {
// Example data: map of field tags to JSON-encoded byte slices
data := map[string]json.RawMessage{
"user_id": []byte(`123`), // Encoded as a JSON number
"message": []byte(`"Hello, world!"`), // Encoded as a JSON string
}
// Convert map to JSON
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("Error marshalling map to JSON:", err)
return
}
// Unmarshal JSON into Tweet struct
var t Tweet
if err := json.Unmarshal(jsonData, &t); err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}
// Output the result
fmt.Printf("Unmarshalled: %+v\n", t)
// Marshal the Tweet struct back into JSON
marshalledData, err := json.Marshal(t)
if err != nil {
fmt.Println("Error marshalling Tweet struct to JSON:", err)
return
}
// Output the marshalled JSON
fmt.Printf("Marshalled: %s\n", marshalledData)
}