在Go语言中,可以使用encoding/json
包来实现[]byte
与JSON之间的转换。
将[]byte
转换为JSON,可以使用json.Marshal()
函数,它接受一个任意类型的值作为参数,返回一个JSON格式的[]byte
。例如:
package main import ( "encoding/json" "fmt" ) func main() { data := []byte("Hello, World!") jsonData, err := json.Marshal(data) if err != nil { fmt.Println("JSON encoding error:", err) return } fmt.Println(string(jsonData)) }
输出结果为:
"SGVsbG8sIFdvcmxkIQ=="
将JSON转换为[]byte
,可以使用json.Unmarshal()
函数,它接受一个JSON格式的[]byte
作为参数,并将JSON解码为相应的Go值。例如:
package main import ( "encoding/json" "fmt" ) func main() { jsonData := []byte(`"SGVsbG8sIFdvcmxkIQ=="`) var data []byte err := json.Unmarshal(jsonData, &data) if err != nil { fmt.Println("JSON decoding error:", err) return } fmt.Println(string(data)) }
输出结果为:
Hello, World!
请注意,在使用json.Unmarshal()
函数时,需要将目标变量的指针作为参数传递给函数。这样才能将解码后的值正确地赋给目标变量。