乐闻世界logo
搜索文章和话题

Golang 中如何处理 JSON 编码和解码?

1个答案

1

In the Go language, handling JSON encoding and decoding primarily relies on the encoding/json standard library. This library provides essential functions and types for processing JSON data. The following outlines the basic steps for using this library to perform JSON encoding and decoding:

JSON Encoding (Marshalling)

JSON encoding refers to converting Go data structures into JSON-formatted strings. You can use the json.Marshal() function to achieve this.

Example:

go
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { person := Person{"Alice", 30} jsonData, err := json.Marshal(person) if err != nil { fmt.Println(err) } fmt.Println(string(jsonData)) }

In this example, we define a Person struct and use json.Marshal() to convert a Person instance into a JSON string. Struct tags like json:"name" specify the JSON key names.

JSON Decoding (Unmarshalling)

JSON decoding refers to converting JSON-formatted strings back into Go data structures. You can use the json.Unmarshal() function to achieve this.

Example:

go
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { jsonData := []byte(`{"name": "Alice", "age": 30}`) var person Person err := json.Unmarshal(jsonData, &person) if err != nil { fmt.Println(err) } fmt.Println(person) }

In this example, we use json.Unmarshal() to decode a JSON string into a Person struct instance. Note that json.Unmarshal() requires a byte slice and a pointer to the target struct.

Handling Errors

During encoding and decoding, if the input data format is invalid or does not match the target structure, both json.Marshal() and json.Unmarshal() return errors. Properly handling these errors is critical for ensuring data integrity and program robustness.

Summary

The Go language's encoding/json library offers simple yet powerful tools for handling JSON data encoding and decoding. By leveraging struct tags, you can easily customize JSON key names, and with json.Marshal() and json.Unmarshal(), you can seamlessly convert data between Go structs and JSON format.

2024年10月26日 16:50 回复

你的答案