2016-09-15 85 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) 
}