Home >Backend Development >Golang >How to perform struct conversion in Golang

How to perform struct conversion in Golang

PHPz
PHPzOriginal
2023-03-22 16:31:492142browse

Golang language is an object-oriented programming language, which has strong readability and maintainability. For most developers, it is more convenient and faster to use Golang for development. In Golang, struct is a very common data type, which can represent a set of attributes of an object. In actual development, it is often necessary to convert between structs. Today we will learn how Golang performs struct conversion.

Define the structure

First, let’s define a structure:

type Person struct {
    Name    string
    Age     int
    Address Address
}

type Address struct {
    Province string
    City     string
    Street   string
}

In the above code, we defined two structures Body, one is Person, which contains three attributes: Name, Age and Address, where Address is a nested structure.

Convert the structure to JSON

In actual development, we often need to convert the structure into JSON format. The built-in encoding/json package in Golang provides convenient JSON encoding and decoding functions. We can use this package to convert structures into JSON format data.

import "encoding/json"

func main() {
    person := Person{Name: "Tom", Age: 18, Address: Address{Province: "Beijing", City: "Beijing", Street: "Wudaokou"}}
    jsonBytes, err := json.Marshal(person)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(jsonBytes))
}

In the above code, we first create a Person instance, and then call json.Marshal() to convert the instance into JSON format data. During the conversion process, if there is an error, an error message will be output, otherwise the string of the converted result will be output.

Convert JSON into a structure

In addition to converting the structure into JSON format, we often need to convert JSON format data into a structure. In the above example, we have converted person into JSON format. Now let's convert the JSON data into a structure.

jsonStr := `{"Name":"Tom","Age":18,"Address":{"Province":"Beijing","City":"Beijing","Street":"Wudaokou"}}`
person := Person{}
err := json.Unmarshal([]byte(jsonStr), &person)
if err != nil {
    fmt.Println(err)
}
fmt.Println(person)

In the above code, we first define the JSON format data as jsonStr, and then call json.Unmarshal() to convert it into a Person structure. Similarly, if an error occurs during the conversion process, the error message is output, otherwise the converted Person structure instance is output.

Field conversion

In some cases, the field names of the data are inconsistent with the field names in the structure. In this case, field conversion is required. In Golang, this can be achieved by changing the attribute name of the structure to Tag.

type Person struct {
    Name    string `json:"name"`
    Age     int    `json:"age"`
    Address Address
}

type Address struct {
    Province string `json:"province"`
    City     string `json:"city"`
    Street   string `json:"street"`
}

In the above code, we added the json tag before the structure attribute name, which specifies the JSON attribute name. During the conversion process, if the tag exists, the tag will prevail.

There is an array in the structure

In the structure, there may be attributes containing arrays. In this case, we need to traverse the array.

type Person struct {
    Name    string    `json:"name"`
    Age     int       `json:"age"`
    Address []Address `json:"address"`
}

type Address struct {
    Province string `json:"province"`
    City     string `json:"city"`
    Street   string `json:"street"`
}

func main() {
    jsonStr := `{"name":"Tom","age":18,"address":[{"province":"Beijing","city":"Beijing","street":"Wudaokou"},{"province":"Henan","city":"Kaifeng","street":"Longting"}]}`
    person := Person{}
    err := json.Unmarshal([]byte(jsonStr), &person)
    if err != nil {
        fmt.Println(err)
    }
    for _, a := range person.Address {
        fmt.Println(a.Province, a.City, a.Street)
    }
}

In the above code, the Person structure contains an array of Address, which we need to traverse. During the conversion process, we can use Unmarshal to convert JSON format data into Person structure instances, and then traverse the Address array to output the Province, City, and Street attributes of each Address instance.

Summary

In Golang, struct conversion is a relatively frequent operation. Through the introduction of this article, we have learned how Golang converts struct and JSON to each other. For some special cases, such as field conversion and array traversal, more in-depth understanding and operation are required. Golang's struct conversion function makes our development more convenient and faster.

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

Statement:
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