slifer2015
slifer2015

Reputation: 762

write custom Marshall and Unmarshaller for proto buf type in golang

I have custom type that I wrote my own Marshall and Unmarshaller And the problem is I Want to do the same using protobuf

I just want to implement the same using protobuf, so that I can implement my own Marshall and Unmarshaller

syntax="proto3";

package main;

message NullInt64{
    bool Valid = 1;
    int64 Int64 = 2;
}

In the way that if the Valid value is false in return the null string

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
}

Upvotes: 5

Views: 4016

Answers (1)

Liyan Chang
Liyan Chang

Reputation: 8061

Protoc will not generate MarshalJSON and UnmarshalJSON functions.

You can:

  1. Use a different protobuf generator (see gogo/protobuf and it's many extensions or fork golang/protobuf to change their generator)

  2. Insert your own functions into the proto package by adding a file to that folder. You can either hand-write or code gen these functions.

Upvotes: 1

Related Questions