douzhuo3233 2013-08-23 04:52
浏览 56
已采纳

使用指针时,omitempty在编码/ xml中不起作用?

I am consuming a REST API that returns XML and am trying to Unmarshal the XML and am having issues that appear that the omitempty is not working. Here is an example of a working XML file:

<?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>

Here is an example of a "bad" record

<?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>

Now I have my structs set up like the following:

 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
 }

Reading through all of the records it works when the XML follows the pattern of the first example <billing></billing> but when it hits a record that has something like <billing/> it throws the following error: panic: runtime error: invalid memory address or nil pointer dereference

Can someone help me figure out what's going on and how to resolve it?

  • 写回答

1条回答 默认 最新

  • doujiayuan8415 2013-08-23 09:37
    关注

    You're probably misunderstanding what ,omitempty means. It takes effect when marshalling data, only. If you unmarshal <billing/> onto a pointer field with ,omitempty, it will still initialize the field. Then, since the XML element is empty, the fields of Billing itself won't be set. In practice, if you assume that customer.Billing != nil means customer.Billing.Address != nil, you'll get the observed panic.

    Note: http://play.golang.org/p/dClkfOVLXh

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?