2016-09-15 86 views
0

有没有一个golang方法,可以让我串行化(串行化)一个去结构。golang字符串结构结构(不含数据)

序列化为零值是一个选项,但是一个很丑的选项。

+0

序列化零值肯定会是最简单的解决方案。 – JimB

+0

可能是其中一个包https://golang.org/pkg/encoding/#pkg-subdirectories – jcbwlkr

回答

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) 
}