Home > Backend Development > Golang > How to convert struct to JSON data in Golang?

How to convert struct to JSON data in Golang?

WBOY
Release: 2024-06-01 13:01:57
Original
531 people have browsed it

In Golang, use the encoding/json package to convert the structure into JSON data. The steps are as follows: Install the encoding/json package. Define the structure. Convert the structure to a JSON string using the json.Marshal() function.

如何在 Golang 中将结构体转换为 JSON 数据?

#How to convert structure to JSON data in Golang?

In Golang, you can use the encoding/json package to convert structures into JSON data. Here's how to do it:

1. Install the package

go get -u encoding/json
Copy after login

2. Define the structure

type Person struct {
    Name string
    Age  int
}
Copy after login

3 . Convert to JSON

Use the json.Marshal() function to convert the structure to a JSON string:

import "encoding/json"

func main() {
    person := Person{Name: "John", Age: 30}

    jsonBytes, err := json.Marshal(person)
    if err != nil {
        // 处理错误
    }

    jsonString := string(jsonBytes)
    fmt.Println(jsonString)
}
Copy after login

Output:

{"Name":"John","Age":30}
Copy after login

Practical case: REST API

The following is a practical case showing how to convert a structure into JSON data in a REST API:

import (
    "encoding/json"
    "net/http"

    "github.com/gorilla/mux"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    router := mux.NewRouter()

    // 路由用于获取单个人的详细信息
    router.HandleFunc("/person/{name}", func(w http.ResponseWriter, r *http.Request) {
        // 从 URL 中获取名称
        name := mux.Vars(r)["name"]

        // 根据名称查询数据库并获取 Person 结构体
        person := getPersonFromDB(name)

        // 将结构体转换为 JSON
        jsonBytes, err := json.Marshal(person)
        if err != nil {
            // 处理错误
        }

        // 将 JSON 发送到客户端
        w.Header().Add("Content-Type", "application/json")
        w.Write(jsonBytes)
    })

    // 启动服务器
    http.ListenAndServe(":8080", router)
}
Copy after login

In this case , when the client makes a GET request to the /person/{name} endpoint, the server queries the database, obtains a Person structure, and then converts the structure to JSON and sends it to the client.

The above is the detailed content of How to convert struct to JSON data in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template