golang stringize结构结构(没有数据)

时间:2016-09-15 20:57:42

标签: serialization go

是否有开箱即用的golang方法,可以让我将字符串化(序列化为字符串)一个go结构。

使用零值进行序列化是一个选项,但是很难看。

1 个答案:

答案 0 :(得分:0)

这是一个示例程序,它使用encoding/json包来序列化和反序列化一个简单的结构。请参阅代码注释以获得解释。

请注意,我在这里省略了错误处理。

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

// your data structure need not be exported, i.e. can have lower case name
// all exported fields will by default be serialized
type person struct {
    Name string
    Age  int
}

func main() {
    writePerson := person{
        Name: "John",
        Age:  32,
    }

    // encode the person as JSON and write it to a bytes buffer (as io.Writer)
    var buffer bytes.Buffer
    _ = json.NewEncoder(&buffer).Encode(writePerson)

    // this is the JSON-encoded text
    // output: {"Name":"John","Age":32}
    fmt.Println(string(buffer.Bytes()))

    // deocde the person, reading from the buffer (as io.Reader)
    var readPerson person
    _ = json.NewDecoder(&buffer).Decode(&readPerson)

    // output: {John 32}
    fmt.Println(readPerson)
}