MCPcopy
hub / github.com/golang/protobuf / marshalAny

Method marshalAny

jsonpb/encode.go:314–370  ·  jsonpb/encode.go::jsonWriter.marshalAny
(m protoreflect.Message, indent string)

Source from the content-addressed store, hash-verified

312}
313
314func (w *jsonWriter) marshalAny(m protoreflect.Message, indent string) error {
315 // "If the Any contains a value that has a special JSON mapping,
316 // it will be converted as follows: {"@type": xxx, "value": yyy}.
317 // Otherwise, the value will be converted into a JSON object,
318 // and the "@type" field will be inserted to indicate the actual data type."
319 md := m.Descriptor()
320 typeURL := m.Get(md.Fields().ByNumber(1)).String()
321 rawVal := m.Get(md.Fields().ByNumber(2)).Bytes()
322
323 var m2 protoreflect.Message
324 if w.AnyResolver != nil {
325 mi, err := w.AnyResolver.Resolve(typeURL)
326 if err != nil {
327 return err
328 }
329 m2 = proto.MessageReflect(mi)
330 } else {
331 mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL)
332 if err != nil {
333 return err
334 }
335 m2 = mt.New()
336 }
337
338 if err := protoV2.Unmarshal(rawVal, m2.Interface()); err != nil {
339 return err
340 }
341
342 if wellKnownType(m2.Descriptor().FullName()) == "" {
343 return w.marshalMessage(m2, indent, typeURL)
344 }
345
346 w.write("{")
347 if w.Indent != "" {
348 w.write("\n")
349 }
350 if err := w.marshalTypeURL(indent, typeURL); err != nil {
351 return err
352 }
353 w.writeComma()
354 if w.Indent != "" {
355 w.write(indent)
356 w.write(w.Indent)
357 w.write(`"value": `)
358 } else {
359 w.write(`"value":`)
360 }
361 if err := w.marshalMessage(m2, indent+w.Indent, ""); err != nil {
362 return err
363 }
364 if w.Indent != "" {
365 w.write("\n")
366 w.write(indent)
367 }
368 w.write("}")
369 return nil
370}
371

Callers 1

marshalMessageMethod · 0.95

Calls 13

DescriptorMethod · 0.95
marshalMessageMethod · 0.95
writeMethod · 0.95
marshalTypeURLMethod · 0.95
writeCommaMethod · 0.95
wellKnownTypeFunction · 0.85
BytesMethod · 0.80
FindMessageByURLMethod · 0.80
InterfaceMethod · 0.80
ResolveMethod · 0.65
UnmarshalMethod · 0.65
StringMethod · 0.45

Tested by

no test coverage detected