在 golang 中为 proto buf 类型编写自定义 Marshall 和 Unmarshaller

sli*_*015 5 go protocol-buffers

我有自己编写的 Marshall 和 Unmarshaller 的自定义类型,问题是我想使用 protobuf 做同样的事情

我只是想使用 protobuf 实现相同的功能,这样我就可以实现我自己的 Marshall 和 Unmarshaller

syntax="proto3";

package main;

message NullInt64{
    bool Valid = 1;
    int64 Int64 = 2;
}
Run Code Online (Sandbox Code Playgroud)

如果 Valid 值为 false,则返回null字符串

type NullInt64 struct {
    Int64 int64
    Valid bool
}

// MarshalJSON try to marshaling to json
func (nt NullInt64) MarshalJSON() ([]byte, error) {
    if nt.Valid {
        return []byte(fmt.Sprintf(`%d`, nt.Int64)), nil
    }

    return []byte("null"), nil
}

// UnmarshalJSON try to unmarshal dae from input
func (nt *NullInt64) UnmarshalJSON(b []byte) error {
    text := strings.ToLower(string(b))
    if text == "null" {
        nt.Valid = false

        return nil
    }

    err := json.Unmarshal(b, &nt.Int64)
    if err != nil {
        return err
    }

    nt.Valid = true
    return nil
}
Run Code Online (Sandbox Code Playgroud)

Liy*_*ang 1

Protoc 不会生成MarshalJSONUnmarshalJSON运行。

你可以:

  1. 使用不同的 protobuf 生成器(请参阅gogo/protobuf及其许多扩展或 fork golang/protobuf 来更改其生成器

  2. 通过将文件添加到该文件夹​​,将您自己的函数插入到proto包中。您可以手写或代码生成这些函数。