美文网首页
go序列化和反序列化的方法

go序列化和反序列化的方法

作者: wu53 | 来源:发表于2017-05-03 18:03 被阅读0次

    下面以json格式为例

    第一种:

        使用tag,这种方法需要对象和对象需要序列化的成员都是是导出的才可以。如

    type Person struct {

        Name string `json:"name"`

        Age  int    `json:"age"`

    }

    第二种:

        有时我们不想导出struct的成员,但又想序列化那些字段的,可实现json包下定义的Marshaler和Unmarshaler接口。

    type person struct {

        name string

        age  int

    }

    func (this person) MarshalJSON() ([]byte, error) {

        coder := new(struct {

             Name string `json:"name"`

             Age  int    `json:"age"`

        })

         coder.Name = this.name

         coder.Age = this.age

         return json.Marshal(coder)

    }

    func (this *person) UnmarshalJSON(in []byte) error {

         decoder := new(struct {

             Name string `json:"name"`

             Age  int    `json:"age"`

         })

        err := json.Unmarshal(in, decoder)

        if err == nil {

             this.name = decoder.Name

             this.age = decoder.Age

            return nil

        }

       return err

    }

    相关文章

      网友评论

          本文标题:go序列化和反序列化的方法

          本文链接:https://www.haomeiwen.com/subject/urdktxtx.html