根据 OpenApi 规范,我在 Quicktype 的帮助下生成了 150 种类型。
当我在 json 中序列化它们时,我可以轻松使用它们,但新客户希望序列化也可以在 xml 中完成。
但失败并显示以下消息:
Failed to marshal XML: xml: unsupported type: map[string]string
因为在我生成的类型中,可能会遇到这样的声明。
这个 xml 问题是已知的,并且在 this Playground 和一些 S.O. 中有一个解决方法。问题。
Playground 建议定义这些方法,用于自定义序列化:
func (m Map) MarshalXML(e *xml.Encoder, start xml.StartElement) error {...}
func (m *Map) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {...}
但是这样做需要我找到一种方法,要求 QuickType 在生成时替换每个
map[string]string
,它将由 main.Map
放置。我怀疑这是可能的。
我首先想知道是否有一种方法可以声明一些
Marshall
、Unmarshall
方法来声明像 map[string]string
这样的“原生 Go 声明”,而无需定义新的类型来关联它们?
然后,
encoder/xml
将在生成时使用这些全局方法来处理map[string]string
,无论它们在哪里遇到。
是否可以在不定义新类型的情况下为map[string]string声明一些Marshall、Unmarshall方法?
没有。
Meta rul:有一些魔术来做某事(有明显的正常解决方案)的概率基本上是 0。