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)
Protoc 不会生成MarshalJSON并UnmarshalJSON运行。
你可以:
使用不同的 protobuf 生成器(请参阅gogo/protobuf及其许多扩展或 fork golang/protobuf 来更改其生成器)
通过将文件添加到该文件夹,将您自己的函数插入到proto包中。您可以手写或代码生成这些函数。
| 归档时间: |
|
| 查看次数: |
3429 次 |
| 最近记录: |