jhump / protoreflect

Reflection (Rich Descriptors) for Go Protocol Buffers
Apache License 2.0
1.35k stars 172 forks source link

how to marshal json for nested message #538

Closed tonglin96 closed 1 year ago

tonglin96 commented 1 year ago

my code:

resp := dynamic.NewMessage(v.Resp)
resp.MarshalJSONPB(&jsonpb.Marshaler{OrigName: true, EmitDefaults: true})

i got: {"history_list":[],"total":"0"} but i want to got like this for nested meesage: {"history_list":[{"id": 0, "name": ""}],"total":"0"}

jhump commented 1 year ago

The history_list field in the example is empty, so it renders as an empty JSON array. This is expected. If you want it to render the list as having a single element (an empty message), you have to add an element to that field.

But it looks like what you are trying to do might already be implemented in grpcurl.MakeTemplate

+resp := grpcurl.MakeTemplate(v.Resp)
+(&jsonpb.Marshaler{OrigName: true, EmitDefaults: true}).MarshalToString(resp)
-resp := dynamic.NewMessage(v.Resp)
-resp.MarshalJSONPB(&jsonpb.Marshaler{OrigName: true, EmitDefaults: true})
tonglin96 commented 1 year ago

The history_list field in the example is empty, so it renders as an empty JSON array. This is expected. If you want it to render the list as having a single element (an empty message), you have to add an element to that field.

But it looks like what you are trying to do might already be implemented in grpcurl.MakeTemplate

+resp := grpcurl.MakeTemplate(v.Resp)
+(&jsonpb.Marshaler{OrigName: true, EmitDefaults: true}).MarshalToString(resp)
-resp := dynamic.NewMessage(v.Resp)
-resp.MarshalJSONPB(&jsonpb.Marshaler{OrigName: true, EmitDefaults: true})

ok, thanks