How to implement JSON encoding and decoding in Golang?
In Golang, you can use the encoding/json package to encode and decode JSON. Here is a simple example:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
// 编码为JSON
person := Person{
Name: "Alice",
Age: 25,
}
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println("JSON encoding error:", err)
return
}
fmt.Println(string(jsonData))
// 解码JSON
var decodedPerson Person
err = json.Unmarshal(jsonData, &decodedPerson)
if err != nil {
fmt.Println("JSON decoding error:", err)
return
}
fmt.Println(decodedPerson)
}
In the example above, we defined a Person structure and specified the corresponding field names in JSON using json tags. Next, we encoded the Person structure into a JSON string using the json.Marshal function, and then decoded the JSON string back into a Person structure using the json.Unmarshal function.
The output result of the above example is:
{"name":"Alice","age":25}
{Name:Alice Age:25}
In this way, we have successfully completed the encoding and decoding of JSON.