MarshalAnypbJSON() marshals an anypb to JSON using the globalPluginSchemaRegistry
(any *anypb.Any)
| 17 | |
| 18 | // MarshalAnypbJSON() marshals an anypb to JSON using the globalPluginSchemaRegistry |
| 19 | func MarshalAnypbJSON(any *anypb.Any) (json.RawMessage, error) { |
| 20 | if any == nil { |
| 21 | return nil, nil |
| 22 | } |
| 23 | // try with the globalPluginSchemaRegistry first |
| 24 | desc := globalPluginSchemaRegistry.FindMessageDescriptorForTypeURL(any.TypeUrl) |
| 25 | if desc != nil && len(any.Value) > 0 { |
| 26 | dynamic := dynamicpb.NewMessage(desc) |
| 27 | if err := proto.Unmarshal(any.Value, dynamic); err == nil { |
| 28 | jsonBytes, e := protojson.MarshalOptions{}.Marshal(dynamic) |
| 29 | if e == nil { |
| 30 | return jsonBytes, nil |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | // fallback to standard anypb.UnmarshalNew() |
| 35 | payload, payloadErr := FromAny(any) |
| 36 | if payloadErr == nil { |
| 37 | if msgI, ok := payload.(MessageI); ok { |
| 38 | msg, err := MarshalJSON(msgI) |
| 39 | if err == nil { |
| 40 | return msg, nil |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | // exit |
| 45 | return nil, fmt.Errorf("unable to marshal any payload type %s to json", any.TypeUrl) |
| 46 | } |
| 47 | |
| 48 | // MarshalAnyProtoJSON() converts an 'any proto' into JSON |
| 49 | func MarshalAnyProtoJSON(any *anypb.Any) (json.RawMessage, error) { |
no test coverage detected