SoFunction
Updated on 2025-03-03

golang Detailed explanation of JSON serialization and deserialization examples

In Go language (commonly known as Golang), JSON (JavaScript Object Notation) is a commonly used data exchange format. The Go standard library providesencoding/jsonPackage, making it very simple and direct to serialization of JSON (converting Go data structures to strings in JSON format) and deserialization of JSON format (converting JSON format strings to Go data structures).

JSON serialization (Marshaling)

Serialization is the process of converting data structures in Go to strings in JSON format. This is usually used for network communication or file storage.

Here is a simple example showing how to serialize a Go structure into a JSON string:

package main
import (
    "encoding/json"
    "fmt"
)
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
func main() {
    user := User{Name: "John Doe", Age: 30}
    // Serialize user objects to JSON    jsonData, err := (user)
    if err != nil {
        // Handle errors        ("Error marshaling JSON:", err)
        return
    }
    // Print JSON string    (string(jsonData))
}

In the above example,Functions are used toUserInstances of the type are converted to JSON-encoded byte slices. If an error occurs during serialization, it returns an error object.

JSON deserialization (Unmarshaling)

Deserialization is the process of converting JSON-formatted strings back to Go's data structures. This is usually used to parse data received from the network or data read from a file.

Here is a simple example showing how to deserialize a JSON string into a Go structure:

package main
import (
    "encoding/json"
    "fmt"
)
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
func main() {
    jsonString := `{"name":"John Doe","age":30}`
    // Create a user object    var user User
    // Deserialize JSON string to user object    err := ([]byte(jsonString), &user)
    if err != nil {
        // Handle errors        ("Error unmarshaling JSON:", err)
        return
    }
    // Print user information    ("Name: %s, Age: %d\n", , )
}

In the above example,Functions are used to parse strings in JSON format toUsertype in variable. If an error occurs during deserialization, it returns an error object.

Error handling and precautions

  • During the process of serialization and deserialization, if you encounter any problems, such as mismatch in the data type or incorrect JSON format,encoding/jsonThe package will return an error. Therefore, in useandWhen , the returned errors should be checked and properly handled.
  • encoding/jsonPackages do not serialize zero-value fields by default when serializing (such as0false""wait). If you need to serialize zero values, you can useomitemptyLabel.
  • During deserialization, if the JSON data contains fields that do not exist in the structure,encoding/jsonThe package ignores these fields. If strict mode is required, you can usejson:"-"Tags to mark fields that should not be ignored.
  • To improve performance, if you need to frequently serialize and deserialize data of the same type, you can consider usingencoding/jsonPackedEncoderandDecoderInterface, which can reduce the overhead of memory allocation and garbage collection.

By using Goencoding/jsonPackage, you can easily process JSON data, whether in client applications, server applications, or other types of Go programs.

This is the article about golang JSON serialization and deserialization. For more related golang JSON serialization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!