【问题标题】:write custom Marshall and Unmarshaller for proto buf type in golang在 golang 中为 proto buf 类型编写自定义 Marshall 和 Unmarshaller
【发布时间】: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


【解决方案1】:

Protoc 不会生成 MarshalJSONUnmarshalJSON 函数。

你可以:

  1. 使用不同的 protobuf 生成器(请参阅 gogo/protobuf 并且有很多 extensions 或 fork golang/protobuf 来更改它们的 generator

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多