1 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
首先,您應(yīng)該了解 DB 列中存儲(chǔ)的內(nèi)容。json.RawMessage
被簡單地定義為type RawMessage []byte
。而且它沒有攜帶足夠的信息來回答你的問題。
我將提供一個(gè)演示來展示它是如何google.protobuf.Any
工作的,這應(yīng)該可以幫助您更好地理解您的問題。
注意事項(xiàng):
Any用于在消息中嵌入其他類型。所以我在演示中?定義了另外兩個(gè)消息(
Foo
和)。Bar
消息
Any
類型允許您將消息用作嵌入式類型而無需其 .proto 定義。Any 包含作為字節(jié)的任意序列化消息,以及充當(dāng)該消息類型的全局唯一標(biāo)識(shí)符并解析為該消息類型的 URL。實(shí)際上,您的問題取決于數(shù)據(jù)庫中存儲(chǔ)的內(nèi)容。請(qǐng)參閱 中的評(píng)論
main.go
。
演示的文件夾結(jié)構(gòu):
├── go.mod
├── main.go
└── pb
? ? ├── demo.pb.go
? ? └── demo.proto
go.mod:
module github.com/ZekeLu/demo
go 1.19
require (
? ? github.com/golang/protobuf v1.5.2
? ? google.golang.org/protobuf v1.28.1
)
pb/demo.proto:
syntax = "proto3";
package pb;
import "google/protobuf/any.proto";
option go_package = "github.com/ZekeLu/demo/pb";
message MyMessage {
? repeated google.protobuf.Any list = 1;
}
message Foo {
? int32 v = 1;
}
message Bar {
? string v = 1;
}
main.go:
package main
import (
? ? "encoding/json"
? ? "fmt"
? ? "google.golang.org/protobuf/types/known/anypb"
? ? "github.com/ZekeLu/demo/pb"
)
func main() {
? ? // If the db stores an instance of pb.Foo, then unmarshal it first.
? ? buf := json.RawMessage([]byte(`{"v":10}`))
? ? var foo pb.Foo
? ? err := json.Unmarshal(buf, &foo)
? ? if err != nil {
? ? ? ? panic(err)
? ? }
? ? // And then marshal it into a new Any instance, which can be used to
? ? // create a slice that can be assigned to pb.MyMessage.List.
? ? a1, err := anypb.New(&foo)
? ? if err != nil {
? ? ? ? panic(err)
? ? }
? ? bar := &pb.Bar{V: "10"}
? ? a2, err := anypb.New(bar)
? ? if err != nil {
? ? ? ? panic(err)
? ? }
? ? // Initialize the List field.
? ? m := pb.MyMessage{List: []*anypb.Any{a1, a2}}
? ? buf, err = json.Marshal(&m)
? ? if err != nil {
? ? ? ? panic(err)
? ? }
? ? fmt.Printf("%s\n", buf)
? ? // Output: {"list":[{"type_url":"type.googleapis.com/pb.Foo","value":"CAo="},{"type_url":"type.googleapis.com/pb.Bar","value":"CgIxMA=="}]}
? ? // If the db stores the output above, it can be unmarshal directly
? ? var m2 pb.MyMessage
? ? err = json.Unmarshal(buf, &m2)
? ? if err != nil {
? ? ? ? panic(err)
? ? }
? ? fmt.Printf("%v\n", m2.List)
? ? // Output: [[type.googleapis.com/pb.Foo]:{v:10} [type.googleapis.com/pb.Bar]:{v:"10"}]
}
運(yùn)行演示的步驟:
$ protoc --proto_path=pb --go_out=pb --go_opt=paths=source_relative demo.proto
$ go mod tidy
$ go run main.go
- 1 回答
- 0 關(guān)注
- 241 瀏覽
添加回答
舉報(bào)