@@ -24,9 +24,8 @@ import (
2424 "encoding/json"
2525 "fmt"
2626
27- protov1 "github.com/golang/protobuf/proto"
2827 "google.golang.org/protobuf/encoding/protojson"
29- protov2 "google.golang.org/protobuf/proto "
28+ "google.golang.org/protobuf/protoadapt "
3029)
3130
3231const jsonIndent = " "
@@ -35,21 +34,14 @@ const jsonIndent = " "
3534//
3635// If marshal fails, it falls back to fmt.Sprintf("%+v").
3736func ToJSON (e any ) string {
38- switch ee := e .(type ) {
39- case protov1.Message :
40- mm := protojson.MarshalOptions {Indent : jsonIndent }
41- ret , err := mm .Marshal (protov1 .MessageV2 (ee ))
42- if err != nil {
43- // This may fail for proto.Anys, e.g. for xDS v2, LDS, the v2
44- // messages are not imported, and this will fail because the message
45- // is not found.
46- return fmt .Sprintf ("%+v" , ee )
47- }
48- return string (ret )
49- case protov2.Message :
37+ if ee , ok := e .(protoadapt.MessageV1 ); ok {
38+ e = protoadapt .MessageV2Of (ee )
39+ }
40+
41+ if ee , ok := e .(protoadapt.MessageV2 ); ok {
5042 mm := protojson.MarshalOptions {
51- Multiline : true ,
5243 Indent : jsonIndent ,
44+ Multiline : true ,
5345 }
5446 ret , err := mm .Marshal (ee )
5547 if err != nil {
@@ -59,13 +51,13 @@ func ToJSON(e any) string {
5951 return fmt .Sprintf ("%+v" , ee )
6052 }
6153 return string (ret )
62- default :
63- ret , err := json .MarshalIndent (ee , "" , jsonIndent )
64- if err != nil {
65- return fmt .Sprintf ("%+v" , ee )
66- }
67- return string (ret )
6854 }
55+
56+ ret , err := json .MarshalIndent (e , "" , jsonIndent )
57+ if err != nil {
58+ return fmt .Sprintf ("%+v" , e )
59+ }
60+ return string (ret )
6961}
7062
7163// FormatJSON formats the input json bytes with indentation.
0 commit comments