我正在使用返回 XML 的 REST API 并尝试解码 XML,但我遇到的问题似乎是 omitempty
不管用。这是一个工作 XML 文件的示例:
<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/339/" id="339">
<name>
<first>Firstname</first>
<last>Lastname</last>
</name>
<email>myemail@example.com</email>
<billing>
<address>
<address1>123 Main St.</address123>
<address2></address2>
<city>Nowhere</city>
<state>IA</state>
<country>USA</country>
<zip>12345</zip>
</address>
</billing>
</customer>
这是一个“坏”记录的例子
<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/6848/" id="6848">
<name>
<first>Firstname</first>
<last>Lastname</last>
</name>
<email/>
<billing/>
</customer>
现在我的结构设置如下:
type Customer struct {
ID int `xml:"id,attr"`
Name *Name `xml:"name,omitempty"`
Billing *Billing `xml:"billing,omitempty"`
}
type Billing struct {
Address *Address `xml:"address,omitempty"`
}
type Address struct {
address_1 string `xml:",omitempty"`
address_2 string `xml:",omitempty"`
city string `xml:",omitempty"`
postal string `xml:",omitempty"`
country string `xml:",omitempty"`
}
type Name struct {
first, last string
}
当 XML 遵循第一个示例的模式时,通读所有有效的记录 <billing></billing>
但是当它达到类似 <billing/>
的记录时它抛出以下错误:panic: runtime error: invalid memory address or nil pointer dereference
谁能帮我弄清楚发生了什么以及如何解决它?
最佳答案
您可能误解了 ,omitempty
是什么方法。它仅在编码 数据时生效。如果你解码 <billing/>
使用 ,omitempty
到指针字段上,它仍然会初始化该字段。然后,由于 XML 元素为空,Billing
的字段本身不会被设置。实际上,如果您假设 customer.Billing != nil
表示 customer.Billing.Address != nil
,你会得到观察到的 panic 。
关于go - 使用指针时,omitempty 在编码/xml 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394911/