【发布时间】:2019-06-02 12:08:42
【问题描述】:
我有自定义类型,我自己编写了 Marshall 和 Unmarshaller 问题是我想使用 protobuf 做同样的事情
我只是想用 protobuf 来实现,这样我就可以实现自己的 Marshall 和 Unmarshaller
syntax="proto3";
package main;
message NullInt64{
bool Valid = 1;
int64 Int64 = 2;
}
如果 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
}
【问题讨论】:
-
我不清楚你在问什么。 “null”字符串不是有效的 protobuf。您可以将您的
NullInt64类型序列化和反序列化为 protobuf。这还不够吗?
标签: go protocol-buffers