This is a creation in
Article, where the information may have evolved or changed.
This article describes how to use the Go language library to convert objects to JSON format, and how to convert data in JSON format to objects
Convert an object to JSON-formatted data
The go language comes with a package that can be used to process data in JSON format
Package Import: Encoding/json
Function prototype: Func Marshal (v interface{}) ([]byte, error)
In the go language, to convert data to JSON format, you can use the Marshal function in the Encoding/json package for data conversion, the Marshal function can receive any type of parameter, after the conversion is complete, return the bytecode array and error information.
The specific source code in the Go language is as follows:
funcinterface{}) ([]byte, error) { e := &encodeState{} true}) ifnil { returnnil, err } returnnil}
Here are the specific usage demos:
type Message struct { Name string Body string Time int64}
- converting data using the Marshal function
Message{"Alice""Hello"1294706395881547000}b, err := json.Marshal(m)
Parsing JSON data
To parse the JSON data, you can use the Unmarshal function in the Encoding/json package to parse the function prototype as follows:
funcUnmarshal(data []byte, v interface{}) error
Specifically, make the example:
- First, you need to create a structure to store the transformed data
varMessage
err := json.Unmarshal(b, &m)