dongyao9762 2015-10-17 05:21
浏览 696
已采纳

Golang序列化/反序列化一个空数组,而不是null

Is there a way to serialize an empty array attribute (not null) of a struct and deserialize it back to an empty array (not null again)?

Considering that an empty array is actually a pointer to null, is the perceptible initial difference between an empty array and pointer to null completely lost after serialize/deserialize?

The worst practical scenario is that when I show an empty array attribute to my REST client, as a json "att":[], at first time, and, after cache register to redis and recover it, the same attribute is shown to my client as "att":null, causing a contract broken and a lot of confusing.

Summing up: is possible to show the Customer 2 addresses like an json empty array, after serialize/deserialize => https://play.golang.org/p/TVwvTWDyHZ

  • 写回答

3条回答 默认 最新

  • doukun0888 2015-10-17 05:37
    关注

    I am pretty sure the easiest way you can do it is to change your line

    var cust1_recovered Customer
    

    to

    cust1_recovered := Customer{Addresses: []Address{}}
    

    Unless I am reading your question incorrectly, I believe this is your desired output:

    ORIGINAL  Customer 2 {
      "Name": "Customer number 2",
      "Addresses": []
    }
    RECOVERED Customer 2 {
      "Name": "Customer number 2",
      "Addresses": []
    }
    

    Here is a playground to verify with: https://play.golang.org/p/T9K1VSTAM0

    The limitation here, as @mike pointed out, is if Addresses is truly nil before you encode, once you decode you do not get the json equivalent null, but would instead end up with an empty list.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?