#In the Go language, serialization and deserialization are usually implemented by converting data into a byte stream (or other transportable format). The following are several commonly used serialization and deserialization methods:
- JSON serialization and deserialization: Go language has a built-in standard library encoding/json, and you can use json.Marshal() to convert data The structure is serialized into a JSON-formatted byte stream. Use json.Unmarshal() to deserialize the JSON-formatted byte stream into a data structure.
import "encoding/json" // 序列化为JSON data, err := json.Marshal(obj) // 反序列化JSON err = json.Unmarshal(data, &obj)
- XML serialization and deserialization: Go language has a built-in standard library encoding/xml, and you can use xml.Marshal() to serialize the data structure into a byte stream in XML format. , use xml.Unmarshal() to deserialize an XML-formatted byte stream into a data structure.
import "encoding/xml" // 序列化为XML data, err := xml.Marshal(obj) // 反序列化XML err = xml.Unmarshal(data, &obj)
- gob serialization and deserialization: Go language has built-in standard library encoding/gob, you can use gob.NewEncoder() and gob.NewDecoder() to create encoders and decoders , call the Encode() and Decode() methods for serialization and deserialization respectively.
import "encoding/gob" // 序列化为字节流 var buffer bytes.Buffer encoder := gob.NewEncoder(&buffer) err = encoder.Encode(obj) data := buffer.Bytes() // 反序列化字节流 decoder := gob.NewDecoder(bytes.NewReader(data)) err = decoder.Decode(&obj)
- Protocol Buffers (protobuf) serialization and deserialization: Go language provides a third-party library github.com/golang/protobuf/proto, which can use the protobuf protocol for efficient serialization ization and deserialization.
import "github.com/golang/protobuf/proto" // 序列化为字节流 data, err := proto.Marshal(obj) // 反序列化字节流 err = proto.Unmarshal(data, obj)
The above are some commonly used serialization and deserialization methods. Choose the appropriate method according to specific needs and scenarios.