Home  >  Article  >  Backend Development  >  How to create custom JSON encoder in Golang?

How to create custom JSON encoder in Golang?

WBOY
WBOYOriginal
2024-06-03 11:18:56515browse

To create a custom JSON encoder in Golang: implement the encoding/json.Marshaler or encoding/json.Unmarshaler interface. The Marshaler interface provides a method to convert a structure into JSON bytes. The Unmarshaler interface provides a method to decode a structure from JSON bytes.

如何在 Golang 中创建自定义 JSON 编码器?

Create a custom JSON encoder in Golang

JSON is a popular method for transmitting data over the network. Format. In Golang, structures can be easily encoded and decoded using the standard library encoding/json. However, sometimes you may need to create a custom encoder to meet specific needs.

Implementing a custom JSON encoder

In order to implement a custom JSON encoder, you need to implement encoding/json.Marshaler or encoding/json.Unmarshaler interface. The

  • Marshaler interface defines a MarshalJSON method that converts a structure to JSON bytes. The
  • Unmarshaler interface defines an UnmarshalJSON method that decodes a structure from JSON bytes.

Here's how to implement a custom JSON encoder:

type User struct {
    ID   int
    Name string
}

// 实现 Marshaler 接口
func (u User) MarshalJSON() ([]byte, error) {
    return []byte(`{"user_id": ` + strconv.Itoa(u.ID) + `,"name": "` + u.Name + `"}`), nil
}

// 实现 Unmarshaler 接口
func (u *User) UnmarshalJSON(data []byte) error {
    var v map[string]interface{}
    if err := json.Unmarshal(data, &v); err != nil {
        return err
    }
    id, ok := v["user_id"].(float64)
    if !ok {
        return fmt.Errorf("invalid user_id")
    }
    u.ID = int(id)
    u.Name = v["name"].(string)
    return nil
}

This encoder encodes and decodes the User structure into JSON fields with a specific format. user_id is encoded as an integer, while name is encoded as a string.

Practical case

In the following example, we use a custom encoder to convert the User structure to JSON bytes:

// 创建一个 User 结构
u := User{
    ID:   1,
    Name: "John Doe",
}

// 转换为 JSON 并打印
jsonBytes, err := json.Marshal(u)
if err != nil {
    panic(err)
}
fmt.Println(string(jsonBytes))

Output:

{"user_id": 1,"name": "John Doe"}

By creating a custom JSON encoder, you can control the format and content of JSON data according to your needs.

The above is the detailed content of How to create custom JSON encoder 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